package grouplife::Controller::Tuans;
use Moose;
use Encode qw(decode);
use namespace::autoclean;
use Catalyst::Request::Upload;
use Catalyst::Log;
use Date::Parse;
use POSIX qw(strftime);

use grouplife::Model::Category::CategoryModel;
use grouplife::Model::Tuan::TuansSearchModel;
use grouplife::Model::Tuan::TuanUtilModel;
use grouplife::Model::Tuan::TuansCreateModel;
use grouplife::Model::UserTuan::UserTuanModel;
use grouplife::Model::UserTuan::UserTuanUpdateModel;
use grouplife::Model::Users::UsersSearchModel;
use grouplife::Model::Comments::CommentsForUsersModel;
use grouplife::Model::Comments::CommentsForTuanModel;
use grouplife::Model::TuanStore::TuanStoreSearchModel;
use grouplife::Model::Leimu::LeimuModel;
use grouplife::Model::Store::StoreSearchModel;
use grouplife::Model::CategoryTuan::CategoryTuanModel;
use grouplife::Model::UserTuanStores::UserTuanStoresModel;
use grouplife::Model::University::UniversityModel;
use grouplife::Model::FaHuo::FaHuoModel;
use grouplife::Model::FaHuoUniversity::FaHuoUniversityModel;
use Util::Email::SendEmail;
use Time::Piece;
use Util::Token::Token;
use Time::Seconds;

BEGIN {extends 'Catalyst::Controller'; }
__PACKAGE__->config( 'Plugin::ConfigLoader' => { file => 'grouplife.yml' } );

=head1 NAME

grouplife::Controller::Tuans - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut

sub index :Path :Args(0) {
    my ( $self, $c ) = @_;

    $c->response->body('Matched grouplife::Controller::Tuans in Tuans.');
}

=head2 list

Fetch all tuans and pass to tuans/list.tt2 in stash to be displayed

=cut

sub list :Local {
	my ($self, $c) = @_;

	$c->stash(login_user => $c->session->{login_user});
	$c->stash(cats => [$c->model('Category::CategoryModel')->get_all]);
	$c->stash(javascript => '/tuan/tuan_search.js');
	$c->stash(template => 'tuans/list.tt2');
}

sub tuan_paging :Local {
	my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
        my $universities = $c->request->params->{"universities[]"} || '0';
        my $zhuangtai = $c->request->params->{"zhuangtai[]"} || '0';

	my %results;
	if ($universities eq '0' or $zhuangtai eq '0') {
		$c->stash(
			login_user => $c->session->{login_user},
			nowrapper => 1,
			template => 'tuans/tuan_search.tt2',
			tuans => \%results
		);
	} else {	
		unless(ref($universities) eq 'ARRAY') {
			my @arr = ($universities);
			$universities= \@arr;
		}
		unless(ref($zhuangtai) eq 'ARRAY') {
			my @arr = ($zhuangtai);
			$zhuangtai= \@arr;
		}
		my $tuans = $c->model('Tuan::TuansSearchModel')->tuan_search($universities, $zhuangtai, $start_index, $end_index);
		my %results;
		my $count = 0;
		foreach (@$tuans) {
			my $status = 'A';
			my $curr_time = `date --iso-8601=seconds`;
			if($_->status eq 'Y') {
				#if(str2time($curr_time) < str2time($_->zhifu_eff_to)) {
				#	$status = 'Z';
				#}elsif(str2time($curr_time) > str2time($_->fahuo_eff_to)) {
				#	$status = 'J';
				if(str2time($curr_time) < str2time($_->tihuo_time_from)) {
					$status = 'W';
				}elsif(str2time($curr_time) > str2time($_->tihuo_time_to)) {
					$status = 'J';
				}else {	
					$status = 'P';
				}	
			}
			if($_->status eq 'N') {
				$status = 'N';
			}
			$results{$count}{"id"} = $_->id;
			$results{$count}{"image"} = $_->image;
			$results{$count}{"name"} = $_->name;
			my @un = $_->university;
			$results{$count}{"university"} = \@un;
			$results{$count}{"status"} = $status;
			my @chengyuan = $_->member;
			if(@chengyuan) {
				$results{$count}{"buyer_count"} = scalar @chengyuan;
			} else {
			       $results{$count}{"buyer_count"} = 0;
			}
			my $total_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_total_amount($_->id);
			my $market_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_total_market_amount($_->id);
			my $saving = $market_amount - $total_amount;
			my $discount = 10;
			if($saving < 0){
				$saving = 0;
			} else {
				if ($market_amount > 1) {
					$discount = $total_amount / $market_amount * 10;
					$discount = sprintf "%0.1f",$discount;
				}
			}
			$results{$count}{"saving"} = $saving;
			$results{$count}{"discount"} = $discount;
			$count ++;
		}

		$c->stash(
			login_user => $c->session->{login_user},
			nowrapper => 1,
			template => 'tuans/tuan_search.tt2',
			tuans => \%results
		);
	}
}

#Autocomplete in tuan search page
sub tuan_names:Local {
	my ($self, $c) = @_;
        my $p = $c->request->params->{q} || '';
	$c->res->output($c->model('Tuan::TuansSearchModel')->get_names_in_json($p));
}

sub user_selected : Local {
	my ($self, $c) = @_;
        my $tuanid = $c->request->params->{tuan_id};
        my $userid = $c->request->params->{user_id};

	$c->res->output($c->model('UserTuan::UserTuanModel')->get_options($userid, $tuanid));
}

sub tuan_search:Local {
	my ($self, $c) = @_;
        my $name = $c->request->params->{content} || '';
	
	my $universities = $c->model('University::UniversityModel')->get_all;

	$c->stash(
		login_user => $c->session->{login_user},
		javascript => '/tuan/tuan_search.js',
		content => $name,
		title => "搜索拼单",
		universities=>$universities,
		css => 'tuan_search.css',
		cats => [$c->model('DB::Category')->all],
		template => 'tuans/list.tt2'
	);
}

sub tuan_total_by_name:Local {
	my ($self, $c) = @_;

        my $name = $c->request->params->{"name"} || '';

	$c->res->output($c->model('Tuan::TuansSearchModel')->get_total_tuan_number_by_name($name));
}
sub tuan_paging_by_name :Local {
	my ($self, $c) = @_;

        my $name = $c->request->params->{"name"} || '';
        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
	my $page = $start_index / 30;
	$page = $page + 1;


	my %results;
	my $tuans = $c->model('Tuan::TuansSearchModel')->tuan_search_by_name($name, $page);
	my $count = 0;
	foreach (@$tuans) {
		my $status = 'A';
		my $curr_time = `date --iso-8601=seconds`;
		if($_->status eq 'Y') {
			#if(str2time($curr_time) < str2time($_->zhifu_eff_to)) {
			#	$status = 'Z';
			#}elsif(str2time($curr_time) > str2time($_->fahuo_eff_to)) {
			#	$status = 'J';
			if(str2time($curr_time) < str2time($_->tihuo_time_from)) {
				$status = 'W';
			}elsif(str2time($curr_time) > str2time($_->tihuo_time_to)) {
				$status = 'J';
			}else {	
				$status = 'P';
			}	
		}
		if($_->status eq 'N') {
			$status = 'N';
		}
		$results{$count}{"id"} = $_->id;
		$results{$count}{"image"} = $_->image;
		$results{$count}{"name"} = $_->name;
		my @un = $_->university;
		$results{$count}{"university"} = \@un;
		$results{$count}{"status"} = $status;
		my @chengyuan = $_->member;
		if(@chengyuan) {
			$results{$count}{"buyer_count"} = scalar @chengyuan;
		} else {
		       $results{$count}{"buyer_count"} = 0;
		}
		my $total_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_total_amount($_->id);
		my $market_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_total_market_amount($_->id);
		my $saving = $market_amount - $total_amount;
		my $discount = 10;
		if($saving < 0){
			$saving = 0;
		} else {
			if ($market_amount > 1) {
				$discount = $total_amount / $market_amount * 10;
				$discount = sprintf "%0.1f",$discount;
			}
		}
		$results{$count}{"saving"} = $saving;
		$results{$count}{"discount"} = $discount;
		$count ++;
	}

	$c->stash(
		login_user => $c->session->{login_user},
		nowrapper => 1,
		template => 'tuans/tuan_search.tt2',
		tuans => \%results
	);
}

sub tuan_total:Local {
	my ($self, $c) = @_;

        my $universities = $c->request->params->{"universities[]"} || '0';
        my $zhuangtai = $c->request->params->{"zhuangtai[]"} || '0';

	if ($universities eq '0' or $zhuangtai eq '0') {
		 $c->res->output(0);
	} else {	
		unless(ref($universities) eq 'ARRAY') {
			my @arr = ($universities);
			$universities= \@arr;
		}
		unless(ref($zhuangtai) eq 'ARRAY') {
			my @arr = ($zhuangtai);
			$zhuangtai= \@arr;
		}
		$c->res->output($c->model('Tuan::TuansSearchModel')->get_total_tuan_number($universities, $zhuangtai));
	}
}

sub store_id:Chained('base'):PathPart('store_id'):CaptureArgs(1){
	my ($self, $c, $id) = @_;

	$c->stash(store => $c->model('Store::StoreSearchModel')->find($id));
}

sub form_create:Local{
	my ($self, $c) = @_;

	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		return 0;
	}
	$c->stash(login_user => $c->session->{login_user});
	$c->stash(template => 'tuans/form_create.tt2');
}

sub base :Chained('/') :PathPart('tuans') :CaptureArgs(0) {
	my ($self, $c) = @_;

	$c->stash(resultset => $c->model('DB::Tuan'));
}

sub comment:Chained('base') :PathPart('comment') :Args(0){
        my ( $self, $c ) = @_;
        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
                return 0;
        }

        my $comment = $c->request->params->{comment}  || '';
        my $comm_id= $c->request->params->{comm_id} || '';
        my $tuan_id= $c->request->params->{tuan_id} || '';
	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
        $c->model('CommentedItem::CommentedItemModel')->add_to_comments($comm_id, $c->user->get('id'), $comment);
	$c->user->add_to_my_news({user_id=>$c->user->id, event_type_id=>5, photo=>$c->user->photo, me_name=>$c->user->username, target_id=>$tuan_id, target_name=>$tuan->name});

	$c->stash(comments => $c->model('Comments::CommentsForUsersModel')->search($comm_id),
		nowrapper=> 1,
		javascript => '/tuan/tuan_info.js',
		template => 'tuans/new_comment.tt2');
}

sub tuan_create : Local{
	my ($self, $c) = @_;
	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		return 0;
	}

	$c->stash(login_user => $c->session->{login_user},
		javascript => '/tuan/tuan_create.js',
		template => 'tuans/tuan_create.tt2');
}

sub join_tuan : Local{
        my ($self, $c) = @_;
	
        my $tuan_id= $c->request->params->{tuan_id};
	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	my $token = Util::Token::Token->new();	
	$c->session->{token} = $token->generate_token();
	$c->stash(token => $c->session->{token});
	if (!$c->user_exists) {
		$c->stash(
			not_login_user => '0',
			javascript => '/tuan/tuan_info.js',
			nowrapper => 1,
			tuan => $tuan,
			template => "tuans/join_tuan.tt2");
		$c->stash(create_new_contact => '1');
		return 0;
	}

        my $user = $c->session->{login_user};
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->find_user_tuan($tuan_id,$user->id,'J');
	my $deliver_contacts = $c->model('UserDeliverContact::UserDeliverContactModel')->find_active_contacts_by_user($user->id);
	if($user_tuan) {
		my $stores = $c->model('UserTuanStores::UserTuanStoresModel')->search($user_tuan->id);
		my $amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_amount_for_user($user->id, $tuan_id);
		my $current_contact = $user_tuan->user_name.$user_tuan->user_address.$user_tuan->user_cellphone;
		my $find_contact = '0';
		foreach(@$deliver_contacts) 
		{
			my $info = $_->user_name.$_->user_address.$_->user_cellphone;
			if($current_contact eq $info) 
			{
				$c->stash(orig_contact_id => $_->id);
				$c->stash(new_contact_id => $_->id);
				$find_contact = '1';
				last;
			}
		}
		if($find_contact eq '0')
		{
			$c->stash(create_new_contact => '1');
		}
		$c->stash(user_tuan => $user_tuan);
		$c->stash(amount => $amount);
		$c->stash(stores => $stores);
	}
	else {
		if(@$deliver_contacts > 0)
		{	
			foreach(@$deliver_contacts) 
			{
				if($_->is_last_used eq 'Y')
				{
					$c->stash(username => $_->user_name);
					$c->stash(useraddress => $_->user_address);
					$c->stash(usercellphone => $_->user_cellphone);
					$c->stash(new_contact_id => $_->id);
					last;
				}
			}
			$c->stash(create_new_contact => '0');
		}
		else
		{
			$c->stash(create_new_contact => '1');
		}
	}	
	$c->stash(login_user => $c->session->{login_user},
		javascript => '/tuan/tuan_info.js',
		nowrapper => 1,
		session_username => $c->session->{$tuan_id}{user_name},
		session_useraddress => $c->session->{$tuan_id}{user_address},
		session_userphone => $c->session->{$tuan_id}{user_phone},
		tuan => $tuan,
		deliver_contacts => $deliver_contacts,
		template => "tuans/join_tuan.tt2");
	
}

sub modify_pay_url : Local{
        my ($self, $c) = @_;
	
	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
		return 0;
	}

	my $tuan_id= $c->request->params->{tuan_id};
	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);

	$c->stash(login_user => $c->session->{login_user},
		javascript => '/tuan/tuan_info.js',
		nowrapper => 1,
		tuan => $tuan,
		template => "tuans/modify_pay_url.tt2");
	
}

sub modify_pay_url_do : Local{
        my ($self, $c) = @_;
	
	my $tuan_id= $c->request->params->{tuan_id};
	my $pay_url= $c->request->params->{pay_url};
	
	$pay_url =~ s/^\s+//;
	$pay_url =~ s/\s+$//;

	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	my $new_url = $pay_url;
	my $old_url = $tuan->pay_url;
	
	unless ($new_url eq $old_url ){
		$tuan->update({pay_url => $new_url});
		$c->stash(login_user => $c->session->{login_user},
			tuan_id => $tuan_id,
			old_url => $old_url,
			tuan_name => $tuan->name,
			css => 'about.css',
			new_url => $new_url,
			template => "tuans/modify_done.tt2");
	} else {
		$c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));
	}
	
}

sub join_tuan_login : Local{
        my ($self, $c) = @_;
	
        my $tuan_id= $c->request->params->{tuan_id};
	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	if (!$c->user_exists) {
		#$c->response->redirect($c->uri_for('/login'));
		#$c->flash->{redirect_after_login} = '' . $c->req->uri;
		$c->stash(
			not_login_user => '0',
			javascript => '/tuan/tuan_info.js',
			nowrapper => 1,
			tuan => $tuan,
			template => "tuans/join_tuan.tt2");
		return 0;
	}
	$c->response->redirect($c->uri_for('/login'));
	$c->flash->{redirect_after_login} = '' . $c->req->base . "tuans/id/$tuan_id/tuan_info";
	return 0;

}

sub join_tuan_do : Local{
        my ($self, $c) = @_;
	
	my $user_id;
        my $amounts = $c->request->params->{'amount[]'};
        my $storeIds = $c->request->params->{'storeId[]'};
        my $tuan_id = $c->request->params->{tuan_id};
        my $create_new_contact = $c->request->params->{create_new_contact};
        my $orig_contact_id = $c->request->params->{orig_contact_id};
        my $new_contact_id = $c->request->params->{new_contact_id};
	my $need_register = '0';
	my $user;
	if (!$c->user_exists) {
		$need_register = '1';
	}
	else {
		$user = $c->session->{login_user};
		$user_id = $user->id;
	}
	my $get_token = $c->request->params->{token} || '';
	my $session_token = $c->session->{token};
        my $token = Util::Token::Token->new();
        $c->session->{token} = $token->generate_token();
        if($get_token eq $session_token) {
		my $rec_user_name = $c->request->params->{dinghuo_name};
		my $rec_user_address = $c->request->params->{address};
		my $rec_user_phone = $c->request->params->{cellphone};
		my $tuan_university = $c->request->params->{university} || '';
		my $email_address = $c->request->params->{email} || '';
		my $join_tuan_comment = $c->request->params->{jtnote} || '';

		unless(ref($storeIds) eq 'ARRAY') {
			my @arr = ($storeIds);
			$storeIds = \@arr;
		}
		unless(ref($amounts) eq 'ARRAY') {
			my @arr = ($amounts);
			$amounts = \@arr;
		}
		my ($message, $storeAmount) = $c->model('Tuan::TuanUtilModel')->check_params($c, $rec_user_name, $rec_user_address, $rec_user_phone, $tuan_university, $need_register, $email_address, $amounts, $storeIds);
		if(scalar(@$message) != 0) {
			$c->session->{$tuan_id}{user_name} = $rec_user_name;
			$c->session->{$tuan_id}{user_address} = $rec_user_address;
			$c->session->{$tuan_id}{user_phone} = $rec_user_phone;

			if($need_register eq '0') {
				$c->stash(login_user => $c->session->{login_user});
			}
			$c->stash(messages => $message);
			$c->stash(css   => 'zhuce.css');
			$c->stash(tuan_id => $tuan_id);
			$c->stash(title => '参拼失败');
			$c->stash(template => 'tuans/join_tuan_failed.tt2');
		} else {	
			my $user_tuan_J;
			my $user_tuan_F;
			if ($need_register eq '0') {
				$user_tuan_J = $c->model('UserTuan::UserTuanModel')->find_user_tuan($tuan_id, $user->id, 'J');
				$user_tuan_F = $c->model('UserTuan::UserTuanModel')->find_user_tuan($tuan_id, $user->id, 'F');
			}
		
			my $rand = new String::Random;
			my $password = $rand->randpattern('nnnnnnnn');
			unless(defined($user_tuan_J) or defined($user_tuan_F)) {
				my $user = $c->model('Tuan::TuanUtilModel')->update_contact_info($c, $need_register,$email_address, $rec_user_phone, $rec_user_name, $rec_user_address, $create_new_contact, $orig_contact_id, $user_id, $tuan_university, $new_contact_id);	
				my $user_tuan;
				if($need_register eq '1')
				{
					$user_id = $user->id;
					$c->authenticate({ email_address => $email_address, active => 'Y', password => $rec_user_phone} );
					$c->session->{login_user} = $user;
					$user_tuan = $c->model('UserTuan::UserTuanUpdateModel')->join_tuan_new($tuan_id, $user_id, $password,$rec_user_name, $rec_user_address, $rec_user_phone, $tuan_university,'N',$join_tuan_comment);
				}
				else
				{
					$user_tuan = $c->model('UserTuan::UserTuanUpdateModel')->join_tuan_new($tuan_id, $user_id, $password,$rec_user_name, $rec_user_address, $rec_user_phone, $tuan_university,'Y',$join_tuan_comment);
				}
				my $ret = $c->model('UserTuanStores::UserTuanStoresModel')->create($user_id, $tuan_id, $storeAmount, $user_tuan->id);

	#Send Email to user
				my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
				my $sender = Util::Email::SendEmail->new();
				my $params = $c->model('Tuan::TuanUtilModel')->send_email_to_anonymous_user($c, $password, $tuan, $user_tuan, $need_register, $rec_user_phone, $sender);
				if($tuan->yuji_tihuo_time =~ /\|/) {
					$c->stash(is_dingqi => "Y");
				}

				$c->stash(yuji_tihuo_time => $params->{yuji_tihuo_time});
				
	#发送提醒邮件给营长
				my $create_user_tuan = $c->model('UserTuan::UserTuanModel')->get_owner($tuan->id);
				my $create_user = $c->model('Users::UsersSearchModel')->find($create_user_tuan->get_column('user_id')->first());
				my %storeNameAmount;
				my %storeNamePrice;
				foreach(keys(%$storeAmount)) {
					my $store = $c->model("Store::StoreSearchModel")->find($_);
					my $amount = $storeAmount->{$_};
					$storeNameAmount{$store->name} = $amount;
					$storeNamePrice{$store->name} = $store->price;
				}
				$c->model('Tuan::TuanUtilModel')->send_email_to_yingzhang($need_register, $c, $create_user, $tuan, $rec_user_name, $rec_user_phone, $rec_user_address, $join_tuan_comment, $params->{yuji_tihuo_time}, $sender, \%storeNameAmount);
				
				$c->stash(login_user => $c->session->{login_user});
				$c->stash(password => $password);
				$c->stash(storeNameAmount => \%storeNameAmount);
				$c->stash(storeNamePrice => \%storeNamePrice);
				$c->stash(css   => 'zhuce.css');
				$c->stash(tuan_id => $tuan_id);
				$c->stash(user => $user);
				$c->stash(title => '参拼成功');
				$c->stash(template => 'tuans/join_tuan_success.tt2');
				if($need_register eq '1') {
					$c->stash(new_password => $rec_user_phone);
					$c->stash(new_emailaddress => $c->user->email_address);
				
				}
				$c->stash(need_register => $need_register);
			} else {
				$c->model('UserTuan::UserTuanModel')->update_contact_info($tuan_id,$user->id,$rec_user_name, $rec_user_address, $rec_user_phone, $tuan_university,$join_tuan_comment);	
				my (%amountUpdate, %amountDelete);
				my $stores_exist = $c->model('UserTuanStores::UserTuanStoresModel')->search($user_tuan_J->id);
				foreach(keys(%$stores_exist)) {
					if(exists $storeAmount->{$_}){ 
						if($stores_exist->{$_} != $storeAmount->{$_}) {
							$amountUpdate{$_} = $storeAmount->{$_};
						}
						delete $storeAmount->{$_};
					} else {
							$amountDelete{$_} = 0;
					}
				}
				my $ret = $c->model('UserTuanStores::UserTuanStoresModel')->create($user->id, $tuan_id, $storeAmount, $user_tuan_J->id);
				$ret = $c->model('UserTuanStores::UserTuanStoresModel')->update($user->id, $tuan_id, \%amountUpdate, $user_tuan_J->id);
				$ret = $c->model('UserTuanStores::UserTuanStoresModel')->delete($user->id, $tuan_id, \%amountDelete, $user_tuan_J->id);
				$c->model('Tuan::TuanUtilModel')->update_contact_info($c, '0',$email_address, $rec_user_phone, $rec_user_name, $rec_user_address, $create_new_contact, $orig_contact_id, $user_id, $tuan_university, $new_contact_id);	
				$c->stash(login_user => $c->session->{login_user});
				$c->stash(css   => 'zhuce.css');
				$c->stash(tuan_id => $tuan_id);
				$c->stash(user => $user);
				$c->stash(title => '修改成功');
				$c->stash(template => 'tuans/update_tuan_success.tt2');
			}
		}
	} else {
		$c->stash(css   => 'zhuce.css');
		$c->stash(login_user => $c->session->{login_user});
		$c->stash(template => 'resubmit/resubmit.tt2');
	}
}

sub exit_tuan : Local{
        my ($self, $c) = @_;
	
        my $tuan_id= $c->request->params->{exit_tuanid};
	
	$c->model('UserTuan::UserTuanUpdateModel')->tuan_delete_user($tuan_id, $c->user->id);
        $c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));
}

sub fuzhi_do : Local {
        my ($self, $c) = @_;

        my $name = $c->request->params->{tuanname};
        my $description = $c->request->params->{neirong};
        my $group_qitian = $c->request->params->{group_qitian} || 'y';
        my $group_tiyan = $c->request->params->{group_tiyan} || '0';
        my $group_zhifu = $c->request->params->{group_zhifu} || 'a';
        my $storeIds = $c->request->params->{"storeId[]"} || '0';
        my $prices = $c->request->params->{"price[]"};
        my $tihuo_location = $c->request->params->{tihuo_location} || '0';
        my $taobao_link = $c->request->params->{taobao_link} || '0';
        my $tiyan_location = $c->request->params->{tiyan_location} || '0';
        my $tiyan_time_from = $c->request->params->{tiyan_time_from} || "1/1/2000 0:0:0";
        my $tiyan_time_to = $c->request->params->{tiyan_time_to} || "1/1/2000 0:0:0";
        my $tihuo_time_from = $c->request->params->{tihuo_time_from} || "1/1/2000 0:0:0";
        my $tihuo_time_to = $c->request->params->{tihuo_time_to} || "1/1/2000 0:0:0";
        my $tuanname = $c->request->params->{tuanname};
        my $universities = $c->request->params->{"university[]"} || '0';

	my @messages;
	if($group_tiyan eq 'y' and $tiyan_location eq '0') {
		my $text = "你选择了为买家提供售前体验，但却没有说明体验地点";
		push(@messages, $text);
	}
	if($group_zhifu eq 'a' and $tihuo_location eq '0') {
			my $text = "你选择了提货时付款，但却没有说明提货地点";
			push(@messages, $text);
	}
	if($group_zhifu eq 'c' and $taobao_link eq '0') {
		my $text = "淘宝支付链接为空";
		push(@messages, $text);
	} else {
		if($group_zhifu eq 'c') {
			unless($taobao_link  =~ /^http:\/\/.*/) {
				my $text = "你输入的淘宝支付链接无效";
				push(@messages, $text);
			}
		}
	}
	my $price_flag = 0;
	if($storeIds eq '0') {
		my $text = "你没有选择任何商品参加本次拼单";
		push(@messages, $text);
	} else {
		unless(ref($prices) eq 'ARRAY') {
			my @arr = ($prices);
			$prices = \@arr;
		}

		foreach (@$prices) {
			unless($_=~ /^[0-9]\d*\.?\d*$/) {
				unless($_ eq '0') {
					$price_flag = 1;
				}
			}
		}
		if($price_flag == 1) {
			my $text = "你输入的商品价格不是合法的数字";
			push(@messages, $text);

		}
	}

	if($universities eq '0') {
		my $text = "你没有选择任何目标高校";
		push(@messages, $text);
	}

	$tiyan_location = '' if ($tiyan_location eq '0');
	$tihuo_location = '' if ($tihuo_location eq '0');
	$taobao_link = '' if ($taobao_link eq '0');

	my ($tiyan_df, $tiyan_dt);
	if($group_tiyan eq 'y') {
		eval{
			$tiyan_df= Time::Piece->strptime($tiyan_time_from, "%m/%e/%Y %H:%M:%S");
			$tiyan_dt = Time::Piece->strptime($tiyan_time_to, "%m/%e/%Y %H:%M:%S");
		};
		if(!$tiyan_df or !$tiyan_dt or $@){
			my $text = "体验时间格式不对";
			push(@messages, $text);

		} else {
			my $diff = $tiyan_dt - $tiyan_df;
			if($diff <= 0) {
				my $text = "体验结束时间应当在开始时间之后";
				push(@messages, $text);
			
			}
		}
	} else {
		$tiyan_df= Time::Piece->strptime("1/1/2000 00:00:00", "%m/%e/%Y %H:%M:%S");
		$tiyan_dt = Time::Piece->strptime("1/1/2000 00:00:00", "%m/%e/%Y %H:%M:%S");
	}

	my ($tihuo_df, $tihuo_dt, $current_time);
	eval{
		$tihuo_df= Time::Piece->strptime($tihuo_time_from, "%m/%e/%Y %H:%M:%S");
		$tihuo_dt = Time::Piece->strptime($tihuo_time_to, "%m/%e/%Y %H:%M:%S");
	};
	if(!$tihuo_df or !$tihuo_dt or $@){
		my $text = "开截团时间格式不对";
		push(@messages, $text);

	} else {
		my $diff = $tihuo_dt - $tihuo_df;
		if($diff <= 0) {
			my $text = "截团时间应当在开团时间之后";
			push(@messages, $text);
		}
	}
	
	if(scalar(@messages) != 0) {
		my $curr_time = `date --iso-8601=seconds`;
		
		$c->stash(login_user => $c->session->{login_user});
		$c->stash(messages => \@messages);
		$c->stash(curr_time => $curr_time);
		$c->stash(css   => 'zhuce.css');
		$c->stash(template => 'tuans/tuan_create_failed.tt2');
		$c->flash(newTuanName => $name);
		$c->flash(newTuanDesc => $description);
		$c->flash(newTuan_qitian => $group_qitian);
		$c->flash(newTuan_tiyan => $group_tiyan);
		$c->flash(newTuan_zhifu => $group_zhifu);
		$c->flash(taobao_link => $taobao_link);
		$c->flash(newTuan_tihuoloc => $tihuo_location);
		$c->flash(newTuan_tiyanloc => $tiyan_location);
		$c->flash(newTuan_tiyantimef => $tiyan_time_from);
		$c->flash(newTuan_tiyantimet => $tiyan_time_to);
		$c->flash(newTuan_tihuotimef => $tihuo_time_from);
		$c->flash(newTuan_tihuotimet => $tihuo_time_to);
		$c->flash(newTuan_univer => $universities);
		$c->flash(newTuan_storeIds => $storeIds);
		$c->flash(newTuan_prices => $prices);
	} else {
		unless(ref($universities) eq 'ARRAY') {
			my @arr = ($universities);
			$universities= \@arr;
		}
		unless(ref($storeIds) eq 'ARRAY') {
			my @arr = ($storeIds);
			$storeIds = \@arr;
		}

		my $commented_item = $c->model('CommentedItem::CommentedItemModel')->create('3');
		my $image = $c->request->upload('tuanimage');
        	my $oldimage = $c->request->params->{oldtuanimage} || "0";

		my $tuan = $c->model('Tuan::TuansCreateModel')->create($image, $c->config->{image_path}, $tuanname, $description, $commented_item->id, $c->user->id, $storeIds, $prices, $group_qitian, $group_tiyan, $group_zhifu, $tihuo_df, $tihuo_dt, $tihuo_location, $tiyan_df, $tiyan_dt, $tiyan_location, $universities, $taobao_link, $oldimage);
		$c->user->add_to_my_news({user_id=>$c->user->id, photo=>$c->user->photo, me_name=>$c->user->username, event_type_id=>3, target_id=>$tuan->id, target_name=>$tuan->name});
		#update status of tuan_zhuanyi_request
		my $tzy_id = $c->request->params->{tzy_id};
		my $user_id = $c->session->{login_user}->id;
		my $request = $c->model('TuanZhuanYi::TuanZhuanYiModel')->update_status($tzy_id,'J',$user_id);
		$c->model('TuanZhuanYi::TuanZhuanYiModel')->update_xiayou_tuan($tzy_id,$tuan->id, $user_id);
		
		$c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan->id]));
		
	}
}

sub create_do : Local{
        my ($self, $c) = @_;
	my $get_token = $c->request->params->{token} || '';

        my $session_token = $c->session->{token};
        my $token = Util::Token::Token->new();
        $c->session->{token} = $token->generate_token();
        if($get_token eq $session_token) {
		my $name = $c->request->params->{tuanname};
		my $description = $c->request->params->{neirong};
		my $group_qitian = $c->request->params->{group_qitian} || 'y';
		my $group_tiyan = $c->request->params->{group_tiyan} || '0';
		my $group_zhifu = $c->request->params->{group_zhifu} || 'a';
		my $storeIds = $c->request->params->{"storeId[]"} || '0';
		my $prices = $c->request->params->{"price[]"};
		my $tihuo_location = $c->request->params->{tihuo_location} || '0';
		my $yuji_tihuo_time = $c->request->params->{yuji_tihuo_time} || '0';
		my $taobao_link = $c->request->params->{taobao_link} || '0';
		my $tiyan_location = $c->request->params->{tiyan_location} || '0';
		my $tiyan_time_from = $c->request->params->{tiyan_time_from} || "1/1/2000 0:0:0";
		my $tiyan_time_to = $c->request->params->{tiyan_time_to} || "1/1/2000 0:0:0";
		my $tihuo_time_from = $c->request->params->{tihuo_time_from} || "1/1/2000 0:0:0";
		my $tihuo_time_to = $c->request->params->{tihuo_time_to} || "1/1/2000 0:0:0";
		my $tuanname = $c->request->params->{tuanname};
		my $receive_notice = $c->request->params->{receive_notice} || 'N';
		my $service_num = $c->request->params->{service_num} || '0';
		my $universities = $c->request->params->{"university[]"} || '0';
		my $fahuoshijians = $c->request->params->{"shijians[]"} || '-1';
		my $dingqi_group = $c->request->params->{dingqi_y} || '0';

		my @messages;
		if($service_num ne '0') {
			my $service_num_flag = 0;
			unless($service_num =~ /^[0-9]\d*\.?\d*$/) {
				$service_num_flag = 1;
			}
			if($service_num_flag == 1) {
				my $text = "你输入的在线客服QQ号不合法";
				push(@messages, $text);
			}
		}
		if($dingqi_group eq 'Y' and $fahuoshijians eq '-1') {
			my $text = "你选择了定期发货，但却没有选择定期的发货时间";
			push(@messages, $text);
		}
		if($dingqi_group eq '0' and $yuji_tihuo_time eq '0') {
			my $text = "你选择了单次发货，但却没有说明具体的发货时间";
			push(@messages, $text);
		}
		if($group_tiyan eq 'y' and $tiyan_location eq '0') {
			my $text = "你选择了为买家提供售前体验，但却没有说明体验地点";
			push(@messages, $text);
		}
		if($group_zhifu eq 'a' and $tihuo_location eq '0') {
				my $text = "你选择了提货时付款，但却没有说明提货地点";
				push(@messages, $text);
		}
		if($group_zhifu eq 'c' and $taobao_link eq '0') {
			my $text = "淘宝支付链接为空";
			push(@messages, $text);
		} else {
			if($group_zhifu eq 'c') {
				unless($taobao_link  =~ /^http:\/\/.*/) {
					my $text = "你输入的淘宝支付链接无效";
					push(@messages, $text);
				}
			}
		}
		my $price_flag = 0;
		if($storeIds eq '0') {
			my $text = "你没有选择任何商品参加本次拼单";
			push(@messages, $text);
		} else {
			unless(ref($prices) eq 'ARRAY') {
				my @arr = ($prices);
				$prices = \@arr;
			}

			foreach (@$prices) {
				unless($_=~ /^[0-9]\d*\.?\d*$/) {
					unless($_ eq '0') {
						$price_flag = 1;
					}
				}
			}
			if($price_flag == 1) {
				my $text = "你输入的商品价格不是合法的数字";
				push(@messages, $text);

			}
		}

		if($universities eq '0') {
			my $text = "你没有选择任何目标高校";
			push(@messages, $text);
		}

		$tiyan_location = '' if ($tiyan_location eq '0');
		$tihuo_location = '' if ($tihuo_location eq '0');
		$taobao_link = '' if ($taobao_link eq '0');

		my ($tiyan_df, $tiyan_dt);
		if($group_tiyan eq 'y') {
			eval{
				$tiyan_df= Time::Piece->strptime($tiyan_time_from, "%m/%e/%Y %H:%M:%S");
				$tiyan_dt = Time::Piece->strptime($tiyan_time_to, "%m/%e/%Y %H:%M:%S");
			};
			if(!$tiyan_df or !$tiyan_dt or $@){
				my $text = "体验时间格式不对";
				push(@messages, $text);

			} else {
				my $diff = $tiyan_dt - $tiyan_df;
				if($diff <= 0) {
					my $text = "体验结束时间应当在开始时间之后";
					push(@messages, $text);
				
				}
			}
		} else {
			$tiyan_df= Time::Piece->strptime("1/1/2000 00:00:00", "%m/%e/%Y %H:%M:%S");
			$tiyan_dt = Time::Piece->strptime("1/1/2000 00:00:00", "%m/%e/%Y %H:%M:%S");
		}

		my ($tihuo_df, $tihuo_dt, $current_time);
		eval{
			$tihuo_df= Time::Piece->strptime($tihuo_time_from, "%m/%e/%Y %H:%M:%S");
			$tihuo_dt = Time::Piece->strptime($tihuo_time_to, "%m/%e/%Y %H:%M:%S");
			#$current_time = Time::Piece->strptime(localtime(), "%m/%e/%Y %H:%M:%S");
		};
		if(!$tihuo_df or !$tihuo_dt or $@){
			my $text = "开截团时间格式不对";
			push(@messages, $text);

		} else {
			my $diff = $tihuo_dt - $tihuo_df;
			if($diff <= 0) {
				my $text = "截团时间应当在开团时间之后";
				push(@messages, $text);
			}
		}
		
		if(scalar(@messages) != 0) {
			my $curr_time = `date --iso-8601=seconds`;
			
			$c->stash(login_user => $c->session->{login_user});
			$c->stash(messages => \@messages);
			$c->stash(curr_time => $curr_time);
			$c->stash(css   => 'zhuce.css');
			$c->stash(template => 'tuans/tuan_create_failed.tt2');
			$c->flash(newTuanName => $name);
			$c->flash(newTuanDesc => $description);
			$c->flash(newTuan_qitian => $group_qitian);
			$c->flash(newTuan_tiyan => $group_tiyan);
			$c->flash(newTuan_zhifu => $group_zhifu);
			$c->flash(taobao_link => $taobao_link);
			$c->flash(newTuan_tihuoloc => $tihuo_location);
			$c->flash(newTuan_tiyanloc => $tiyan_location);
			$c->flash(newTuan_tiyantimef => $tiyan_time_from);
			$c->flash(newTuan_tiyantimet => $tiyan_time_to);
			$c->flash(newTuan_tihuotimef => $tihuo_time_from);
			$c->flash(newTuan_tihuotimet => $tihuo_time_to);
			$c->flash(newTuan_univer => $universities);
			$c->flash(newTuan_storeIds => $storeIds);
			$c->flash(newTuan_prices => $prices);
			$c->flash(newTuan_yuji_tihuo_time => $yuji_tihuo_time);
			$c->flash(newTuan_service_num => $service_num);
		} else {
			unless(ref($universities) eq 'ARRAY') {
				my @arr = ($universities);
				$universities= \@arr;
			}
			unless(ref($storeIds) eq 'ARRAY') {
				my @arr = ($storeIds);
				$storeIds = \@arr;
			}

			my $commented_item = $c->model('CommentedItem::CommentedItemModel')->create('3');
			my $image = $c->request->upload('tuanimage');
			my $oldimage = $c->request->params->{oldtuanimage} || "0";

			if($fahuoshijians ne '-1') {
				$dingqi_group = 'Y';
				if(ref($fahuoshijians) eq 'ARRAY') {
					my $fahuocount = scalar(@$fahuoshijians);
					$yuji_tihuo_time = "";
					while($fahuocount > 0) {
                				my $shijian = $fahuoshijians->[$fahuocount - 1];
                				$yuji_tihuo_time = $yuji_tihuo_time . "|" . $shijian;
						$fahuocount = $fahuocount - 1;
        				}
				}
				else {
					if(($fahuoshijians >= 1) && ($fahuoshijians <= 7)) {
                				$yuji_tihuo_time = "|" . $fahuoshijians;
					}
					else {
						$yuji_tihuo_time = $fahuoshijians;
					}
				}
			}
			else {
				(my $dmonth, my $dday,my $dyear) = split(/\//, $yuji_tihuo_time);
				(my $dyear1, my $dtime)  = split(/ /, $dyear);
				$yuji_tihuo_time = $dyear1 . "-" . $dmonth . "-" . $dday;
			}	
			my $tuan = $c->model('Tuan::TuansCreateModel')->create($image, $c->config->{image_path}, $tuanname, $description, $commented_item->id, $c->user->id, $storeIds, $prices, $group_qitian, $group_tiyan, $group_zhifu, $tihuo_df, $tihuo_dt, $tihuo_location, $tiyan_df, $tiyan_dt, $tiyan_location, $universities, $taobao_link, $oldimage,$receive_notice, $yuji_tihuo_time,$dingqi_group);
			if($service_num ne '0') {
				my $service = $c->model('OnlineService::OnlineServiceModel')->create('-1',$tuan->id,$service_num);
			}
			$c->user->add_to_my_news({user_id=>$c->user->id, photo=>$c->user->photo, me_name=>$c->user->username, event_type_id=>3, target_id=>$tuan->id, target_name=>$tuan->name});
			$c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan->id]));
		}
	} else {
		$c->stash(css   => 'zhuce.css');
		$c->stash(login_user => $c->session->{login_user});
		$c->stash(template => 'resubmit/resubmit.tt2');
	}
}

sub object :Chained('base') :PathPart('id') :CaptureArgs(1) {
	my ($self, $c, $id) = @_;

	$c->stash(object => $c->stash->{resultset}->find($id));

	die "Tuan $id not found!" if !$c->stash->{object};

}

sub tuan_info :Chained('object') :PathPart('tuan_info') :Args(0) {
	my ($self, $c) = @_;

	$c->cache_page( $c->config->{time_out} );
	$c->model('Tuan::TuansCreateModel')->update_counter($c->stash->{object});
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->get_owner($c->stash->{object}->id);
	my $tuan_name = $c->stash->{object}->name;

	my $create_user = $c->model('Users::UsersSearchModel')->find($user_tuan->get_column('user_id')->first()); 

	my $login_user_role = $c->model('UserTuan::UserTuanModel')->get_login_user_role($c->stash->{object}->id, $c->user, $c->session->{login_user});
	my $role = $c->model('UserTuan::UserTuanModel')->get_login_user_role_from_table($c->user, $c->session->{login_user});

	if($c->user_exists) {
		my $login_user_tuan = $c->model('UserTuan::UserTuanModel')->find_user_tuan($c->stash->{object}->id, $c->user->id, 'F');
		$c->stash(login_user_tuan_id => $login_user_tuan->id) if($login_user_tuan);
	}
	my $owner_tuanzhang_info = $c->model('TuanZhang::TuanZhangModel')->tuanzhang_request_search($create_user->id);	
	my $owner_renzheng_status = 'U'; #'U'表示未提交申请
        if (defined $owner_tuanzhang_info) {
                $owner_renzheng_status = $owner_tuanzhang_info->status;
        }
	my $yuji_tihuo_time = $c->stash->{object}->yuji_tihuo_time;
	if(defined($yuji_tihuo_time) and $yuji_tihuo_time =~ /\|/) {
		my @dingqi_tihuo_times =split(/|/,$yuji_tihuo_time); 

		my $t = localtime;
		my $current_day_of_week = $t->day_of_week;
		my $next_weekday;
		my $current_next_weekday = 8;
		my $min_weekday = 7;
		my $is_next_week = 0;
		my $day_count = 0;
		foreach(@dingqi_tihuo_times) {
			if($day_count % 2 == 1) {
				if($_ > $current_day_of_week) {
					$next_weekday = $_;
					if($next_weekday < $current_next_weekday) {
						$current_next_weekday = $next_weekday;
					}
				}
				if($_ < $min_weekday) {
					$min_weekday = $_;
				}
			}
			$day_count = $day_count + 1;
		}
		my $time_diff;
		if($current_next_weekday <= 7) {
			$time_diff = $current_next_weekday - $current_day_of_week;	
		}
		else {
			$time_diff = $min_weekday + 7 - $current_day_of_week;
		}
		my $yuji_time = localtime;
		
		while($time_diff > 0) {
			$yuji_time += ONE_DAY;	
			$time_diff = $time_diff - 1;
		}
		$yuji_tihuo_time = $yuji_time->ymd;
	}
	
	my @xiayou_tuan_ids = $c->model('TuanZhuanYi::TuanZhuanYiModel')->find_xiayou_tuan_id($c->stash->{object}->id);	
	my @xiayou_tuans;
	my %xiayou_univs;
	my $is_upstream = '0';
	foreach my $xid(@xiayou_tuan_ids) {
		my $xt = $c->model('Tuan::TuansSearchModel')->find($xid);
		if(defined $xt) {
			if($xt->status . '' eq 'Y') {
				push(@xiayou_tuans, $xt);
				$is_upstream = '1';
			}
		}
	}
	my $shangyou_tuan_id = $c->model('TuanZhuanYi::TuanZhuanYiModel')->find_shangyou_tuan_id($c->stash->{object}->id);	
	my @shangyou_tuans;
	my $st = $c->model('Tuan::TuansSearchModel')->find($shangyou_tuan_id);
	my $is_downstream = '0';
	if (defined $st) {
		push(@shangyou_tuans, $st);
		$is_downstream = '1';
	}
	my $user_count = $c->model('UserTuanStores::UserTuanStoresModel')->get_user_count($c->stash->{object}->id);
	my $buy_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_amount($c->stash->{object}->id);
	my $chengyuan = $c->model('UserTuanStores::UserTuanStoresModel')->get_chengyuan($c->stash->{object}->id);
	my $total_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_total_amount($c->stash->{object}->id);
	my $market_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_total_market_amount($c->stash->{object}->id);
	my $saving = $market_amount - $total_amount;
	my $discount = 10;
	if($saving < 0){
		$saving = 0;
	} else {
		if ($market_amount > 1) {
			$discount = $total_amount / $market_amount * 10;
			$discount = sprintf "%0.1f",$discount;	
		}
	}

	my @fahuo_records = $c->model('FaHuo::FaHuoModel')->fahuo_search($c->stash->{object}->id);	
	
	my @fahuo_universities;

	foreach my $fahuo (@fahuo_records) {
		my @fahuo_univs = $c->model('FaHuoUniversity::FaHuoUniversityModel')->fahuo_univ_search($fahuo->id);	
                push(@fahuo_universities, @fahuo_univs);
	}
	my $total_count = 0;
	if(defined($chengyuan)) {
		$total_count = scalar(@$chengyuan);
	}

#decide whether it is out of date
	my $my_tuan = $c->stash->{object};
	my $status = 'A';
	my $curr_time = `date --iso-8601=seconds`;
	if($my_tuan->status eq 'Y') {
		#if(str2time($curr_time) < str2time($my_tuan->zhifu_eff_to)) {
		#	$status = 'Z';
		#}elsif(str2time($curr_time) > str2time($my_tuan->fahuo_eff_to)) {
		#	$status = 'J';
		# W表示尚未开团
		if(str2time($curr_time) < str2time($my_tuan->tihuo_time_from)) {
			$status = 'W';
		# J表示拼单已截团中
		}elsif(str2time($curr_time) > str2time($my_tuan->tihuo_time_to)) {
			$status = 'J';
		# P表示拼单进行中
		}else {	
			$status = 'P';
		}	
	}
	if($my_tuan->status eq 'N') {
		$status = 'N';
	}
	if($my_tuan->status eq 'I') {
		$status = 'I';
	}
	
	my $current_tuan_id = $c->stash->{object}->id;
	if($c->session->{login_user}) {
		my $user_id = $c->session->{login_user}->id;
		my $tuanzhang_info = $c->model('TuanZhang::TuanZhangModel')->tuanzhang_request_search($user_id);
		my $renzheng_status = 'U'; #'U'表示未提交申请
		if (defined $tuanzhang_info) {
			$renzheng_status = $tuanzhang_info->status;
		}
		$c->stash(renzheng_status => $renzheng_status);
		my $current_user_id = $c->session->{login_user}->id;	
		my $credit_tz = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_user_tuan_type($current_user_id,$current_tuan_id,1);
		my $credit_cp = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_user_tuan_type($current_user_id,$current_tuan_id,2);
		my $credit_fh = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_user_tuan_type($current_user_id,$current_tuan_id,3);
		my $credit_fw = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_user_tuan_type($current_user_id,$current_tuan_id,4);
		$c->stash(credit_tz => $credit_tz);
		$c->stash(credit_cp => $credit_cp);
		$c->stash(credit_fh => $credit_fh);
		$c->stash(credit_fw => $credit_fw);
	}
	my @tuan_credit_tzs = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_tuan_type($current_tuan_id,1);
	my @tuan_credit_cps = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_tuan_type($current_tuan_id,2);
	my @tuan_credit_fhs = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_tuan_type($current_tuan_id,3);
	my @tuan_credit_fws = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_tuan_type($current_tuan_id,4);
	if(@tuan_credit_tzs > 0)
	{
		my $total_tuan_credit_tz = 0;
		my $tz_count = 0;
		foreach(@tuan_credit_tzs)
		{
			$total_tuan_credit_tz += $_->credit;
			$tz_count += 1;
		}
		my $tz_av = $total_tuan_credit_tz/$tz_count;
		$tz_av = sprintf "%0.2f",$tz_av;
		$c->stash(credit_tz_av => $tz_av);
		my $comment_count = @tuan_credit_tzs;
		$c->stash(comment_count => $comment_count);
	}
	if(@tuan_credit_cps > 0)
	{
		my $total_tuan_credit_cp = 0;
		my $cp_count = 0;
		foreach(@tuan_credit_cps)
		{
			$total_tuan_credit_cp += $_->credit;
			$cp_count += 1;
		}
		my $cp_av = $total_tuan_credit_cp/$cp_count;
		$cp_av = sprintf "%0.2f",$cp_av;
		$c->stash(credit_cp_av => $cp_av);
	}
	if(@tuan_credit_fhs > 0)
	{
		my $total_tuan_credit_fh = 0;
		my $fh_count = 0;
		foreach(@tuan_credit_fhs)
		{
			$total_tuan_credit_fh += $_->credit;
			$fh_count += 1;
		}
		my $fh_av = $total_tuan_credit_fh/$fh_count;
		$fh_av = sprintf "%0.2f", $fh_av;
		$c->stash(credit_fh_av => $fh_av);
	}
	if(@tuan_credit_fws > 0)
	{
		my $total_tuan_credit_fw = 0;
		my $fw_count = 0;
		foreach(@tuan_credit_fws)
		{
			$total_tuan_credit_fw += $_->credit;
			$fw_count += 1;
		}
		my $fw_av = $total_tuan_credit_fw/$fw_count;
		$fw_av =  sprintf "%0.2f", $fw_av;
		$c->stash(credit_fw_av => $fw_av);
	}
	my $cantuan_renci =  $c->model('UserTuan::UserTuanModel')->find_user_tuan_count($c->stash->{object}->id) - 1;
	my $service_qq;
	my $service_qq1 =  $c->model('OnlineService::OnlineServiceModel')->get_service_num_by_tuan($c->stash->{object}->id);
	if(!defined($service_qq1)) {
		foreach($my_tuan->university)
		{
			$service_qq1 =  $c->model('OnlineService::OnlineServiceModel')->get_service_num_by_university($_->id);
			if(defined($service_qq1))
			{
				$service_qq = $service_qq1->get_column('service_num'); 
			}
		}
	}
	else 
	{
		$service_qq = $service_qq1->get_column('service_num'); 
	}
	if(!defined($service_qq)) {
		my $service_qq1 =  $c->model('OnlineService::OnlineServiceModel')->get_service_num_by_university(-1);
		$service_qq = $service_qq1->get_column('service_num'); 
	}

	$c->stash(login_user_role => $login_user_role,
		role => $role,
		service_qq => $service_qq,
		tuanid => $c->stash->{object}->id,
		tuanname => $c->stash->{object}->name,
		login_user => $c->session->{login_user},
		create_user => $create_user,
		tuan => $c->stash->{object},
		css => 'tuan_mainpage.css',
		total_count => $total_count,
		title => $tuan_name,
		status => $status,
		discount => $discount,
		market_amount => $market_amount,
		saving => $saving,
		user_count => $user_count,
		buy_amount => $buy_amount,
		chengyuan => $chengyuan,
		renci => $cantuan_renci,
		total_amount => $total_amount,
		fahuo_records => \@fahuo_records,
		fahuo_univs => \@fahuo_universities,
		shangyou_tuans => \@shangyou_tuans,
		xiayou_tuans => \@xiayou_tuans,
		is_downstream => $is_downstream,
		yuji_tihuo_time => $yuji_tihuo_time,
		is_upstream => $is_upstream,
		owner_renzheng_status => $owner_renzheng_status,
		javascript => '/tuan/tuan_info.js',
		template => 'tuans/tuan_mainpage.tt2');
}

sub comment_list:Local {
        my ($self, $c) = @_;
        my $tuan_id = $c->request->params->{tuan_id};
        my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id);
	my $create_user = $c->model('Users::UsersSearchModel')->find($user_tuan->get_column('user_id')->first()); 
	my @tuan_credit_tzs = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_tuan_type($tuan_id,1);
	my @tuan_credit_cps = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_tuan_type($tuan_id,2);
	my @tuan_credit_fhs = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_tuan_type($tuan_id,3);
	my @tuan_credit_fws = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_tuan_type($tuan_id,4);
	my %credits_tzs;
	my %credits_cps;
	my %credits_fhs;
	my %credits_fws;
	my %users;
	foreach(@tuan_credit_tzs) {
		$credits_tzs{$_->user_id} = $_->credit;	
		my $user = $c->model('Users::UsersSearchModel')->find($_->user_id); 
		$users{$_->user_id} = $user;
	}
	foreach(@tuan_credit_cps) {
		$credits_cps{$_->user_id} = $_->credit;	
	}
	foreach(@tuan_credit_fhs) {
		$credits_fhs{$_->user_id} = $_->credit;	
	}
	foreach(@tuan_credit_fws) {
		$credits_fws{$_->user_id} = $_->credit;	
	}
	$c->stash(
		login_user => $c->session->{login_user},
		tuan => $tuan,
		tuanzhang => $create_user,
		css => 'tuan_mainpage.css',
		credits_tzs => \%credits_tzs, 
		credits_cps => \%credits_cps, 
		credits_fhs => \%credits_fhs, 
		credits_fws => \%credits_fws, 
		users => \%users,
		#javascript => '/tuan/buyer_detail_list.js',
		template => 'tuans/comment_list.tt2');
}

sub pingjia_tuanzhang:Local {
        my ($self, $c) = @_;
        my $tuan_id = $c->request->params->{tuanid};
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id);
	my $create_user = $c->model('Users::UsersSearchModel')->find($user_tuan->get_column('user_id')->first()); 
	my $tz_credit = $c->request->params->{tz_credit};
	my $cp_credit = $c->request->params->{cp_credit};
	my $fh_credit = $c->request->params->{fh_credit};
	my $fw_credit = $c->request->params->{fw_credit};
	my $current_user_id = $c->session->{login_user}->id;	
	my $credit_tz = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_user_tuan_type($current_user_id,$tuan_id,1);
	if(defined($credit_tz)) {
		$c->model('CreditTuanZhang::CreditTuanZhangModel')->update(1,$tz_credit,$tuan_id, $current_user_id);
	}else {
		$c->model('CreditTuanZhang::CreditTuanZhangModel')->create(1,$tz_credit,$create_user->id,$tuan_id, $current_user_id);
	}
	my $credit_cp = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_user_tuan_type($current_user_id,$tuan_id,2);
	if(defined($credit_cp)) {
		$c->model('CreditTuanZhang::CreditTuanZhangModel')->update(2,$cp_credit,$tuan_id, $current_user_id);
	}else {
		$c->model('CreditTuanZhang::CreditTuanZhangModel')->create(2,$cp_credit,$create_user->id,$tuan_id, $current_user_id);
	}
	my $credit_fh = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_user_tuan_type($current_user_id,$tuan_id,3);
	if(defined($credit_fh)) {
		$c->model('CreditTuanZhang::CreditTuanZhangModel')->update(3,$fh_credit,$tuan_id, $current_user_id);
	}else {
		$c->model('CreditTuanZhang::CreditTuanZhangModel')->create(3,$fh_credit,$create_user->id,$tuan_id, $current_user_id);
	}
	my $credit_fw = $c->model('CreditTuanZhang::CreditTuanZhangModel')->find_credit_by_user_tuan_type($current_user_id,$tuan_id,4);
	if(defined($credit_fw)) {
		$c->model('CreditTuanZhang::CreditTuanZhangModel')->update(4,$fw_credit,$tuan_id, $current_user_id);
	}else {
		$c->model('CreditTuanZhang::CreditTuanZhangModel')->create(4,$fw_credit,$create_user->id,$tuan_id, $current_user_id);
	}
       	$c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));
}

sub buyer_list:Local {
        my ($self, $c) = @_;
        my $tuan_id = $c->request->params->{tuan_id};
        my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);

	my $user_count = $c->model('UserTuanStores::UserTuanStoresModel')->get_user_count($tuan_id);
	my $buy_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_amount($tuan_id);
	my $yifahuo_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_yifahuo_amount($tuan_id);
	my $weifahuo_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_weifahuo_amount($tuan_id);
	my $buyer_details = $c->model('UserTuanStores::UserTuanStoresModel')->get_user_buy_details($tuan_id);
	my $bianhao = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_bianhao($tuan_id);
	my $price = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_price($tuan_id);
	my $owner_id = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id)->get_column('user_id')->first();
	my @user_tuans = $c->model('UserTuan::UserTuanModel')->find_user_tuan_by_tuan_id($tuan_id);
	my $fahuo_count = $c->model('FaHuo::FaHuoModel')->find_next_fahuo_count($tuan_id);
	
	my %tmp;
	foreach ($tuan->users) {
		$tmp{$_->id} = $_;
	}

	my %users;
	my %user_tuan_id_hash;
	my %new_user_tuans;
	foreach (@user_tuans) {
		my $user_name = $tmp{$_->user_id};
		#$user_name = $user_name . "|" . $_->id;
		$user_name = $_->id . "|" . $user_name;
		$users{$user_name} = $tmp{$_->user_id};
		$user_tuan_id_hash{$user_name} = $_->id;
		$new_user_tuans{$_->id} = $_;
	}

	my @sortorder = sort keys %users;	
	my $status = 'A';
	my $curr_time = `date --iso-8601=seconds`;
	if($tuan->status eq 'Y') {
		if(str2time($curr_time) < str2time($tuan->tihuo_time_from)) {
			$status = 'W';
		# J表示拼单已截团中
		}elsif(str2time($curr_time) > str2time($tuan->tihuo_time_to)) {
			$status = 'J';
		# P表示拼单进行中
		}else {	
			$status = 'P';
		}	
	}
	if($tuan->status eq 'N') {
		$status = 'N';
	}
	$c->stash(
		login_user => $c->session->{login_user},
		tuan => $tuan,
		css => 'tuan_mainpage.css',
		user_count => $user_count,
		owner_id => $owner_id,
		buy_amount => $buy_amount,
		sort_keys => \@sortorder,
		weifahuo_amount => $weifahuo_amount,
		yifahuo_amount => $yifahuo_amount,
		title => $tuan->name,
		users => \%users,
		fahuo_count => $fahuo_count,
		user_tuan_id_hash => \%user_tuan_id_hash,
		buyer_details => $buyer_details,
		bianhao => $bianhao,
		status => $status,
		price => $price,
		javascript => '/tuan/buyer_detail_list.js',
		user_tuans => \%new_user_tuans,
		template => 'tuans/buyer_list_detailed.tt2');
}

sub comments_total:Local {
        my ($self, $c) = @_;
        my $tuan_id = $c->request->params->{tuan_id};
        my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
        $c->res->output($c->model('Comments::CommentsForTuanModel')->get_comm_count($tuan->comm_item_id));
}

sub comments_paging :Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
        my $tuan_id = $c->request->params->{tuan_id};
	my $owner_id = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id)->get_column('user_id')->first();	

        my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
        my $page = $start_index / 10;
        $page = $page + 1;
        $c->stash(
                nowrapper => 1,
		owner_id => $owner_id,
		comments => $c->model('Comments::CommentsForTuanModel')->search($tuan->comm_item_id, $page),
                template => 'tuans/user_comments.tt2'
        );
}

sub chehui_tuan:Local {
	my ($self, $c) = @_;
	
	my $tuan_id = $c->request->params->{tuan_id};
	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);

	if($tuan->status eq 'Y' or $tuan->status eq 'N') {
		my $text = "你的拼单已经被审批，目前不能修改";	
	        $c->stash(login_user => $c->session->{login_user});
                $c->stash(message => $text);
                $c->stash(title => '撤回失败');
                $c->stash(css   => 'zhuce.css');
                $c->stash(tuan_id   => $tuan_id);
                $c->stash(template => 'tuans/tuan_edit_failed_1.tt2');	
		return 1;
	}
	$tuan = $c->model('Tuan::TuansCreateModel')->update_status('I', $tuan_id);
       	$c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));
	
}

sub update_tuan:Local {
	my ($self, $c) = @_;

	my $name = $c->request->params->{tuanname};
        my $description = $c->request->params->{neirong};
        my $group_qitian = $c->request->params->{group_qitian} || 'y';
        my $group_tiyan = $c->request->params->{group_tiyan} || '0';
        my $group_zhifu = $c->request->params->{group_zhifu} || 'a';
        my $storeIds = $c->request->params->{"storeId[]"} || '0';
        my $prices = $c->request->params->{"price[]"};
        my $tihuo_location = $c->request->params->{tihuo_location} || '0';
        my $yuji_tihuo_time = $c->request->params->{yuji_tihuo_time} || '0';
        my $tiyan_location = $c->request->params->{tiyan_location} || '0';
        my $tiyan_time_from = $c->request->params->{tiyan_time_from} || "1/1/2000 0:0:0";
        my $tiyan_time_to = $c->request->params->{tiyan_time_to} || "1/1/2000 0:0:0";
        my $tihuo_time_from = $c->request->params->{tihuo_time_from} || "1/1/2000 0:0:0";
        my $tihuo_time_to = $c->request->params->{tihuo_time_to} || "1/1/2000 0:0:0";
        my $tuanname = $c->request->params->{tuanname};
        my $service_num = $c->request->params->{service_num};
        my $universities = $c->request->params->{"university[]"} || '0';
	my $receive_notice = $c->request->params->{receive_notice} || 'N';
	my $tuan_id = $c->request->params->{tuan_id};
	my $fahuoshijians = $c->request->params->{"shijians[]"} || '-1';
	my $dingqi_group = $c->request->params->{dingqi_y} || '0';
	
	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);

	if($tuan->status eq 'Y') {
		my $text = "你的拼单已经审批通过了，目前不能修改";	
	        $c->stash(login_user => $c->session->{login_user});
                $c->stash(message => $text);
                $c->stash(title => '修改失败');
                $c->stash(css   => 'zhuce.css');
                $c->stash(tuan_id   => $tuan_id);
                $c->stash(template => 'tuans/tuan_edit_failed_1.tt2');	
		return 1;
	}
	my @messages;
	if($service_num ne '0') {
		my $service_num_flag = 0;
		unless($service_num =~ /^[0-9]\d*\.?\d*$/) {
			$service_num_flag = 1;
		}
		if($service_num_flag == 1) {
			my $text = "你输入的在线客服QQ号不合法";
			push(@messages, $text);
		}
	}
	if($dingqi_group eq 'Y' and $fahuoshijians eq '-1') {
		my $text = "你选择了定期发货，但却没有选择定期的发货时间";
		push(@messages, $text);
	}
	if($dingqi_group eq '0' and $yuji_tihuo_time eq '0') {
		my $text = "你选择了单次发货，但却没有说明具体的发货时间";
		push(@messages, $text);
	}
        if($group_tiyan eq 'y' and $tiyan_location eq '0') {
                my $text = "你选择了为买家提供售前体验，但却没有说明体验地点";
                push(@messages, $text);
        }
        if($group_zhifu eq 'a' and $tihuo_location eq '0') {
                my $text = "你选择了提货时付款，但却没有说明提货地点";
                push(@messages, $text);
        }
        if($storeIds eq '0') {
                my $text = "你没有选择任何商品参加本次拼单";
                push(@messages, $text);
        }
        if($universities eq '0') {
                my $text = "你没有选择任何目标高校";
                push(@messages, $text);
        }
	unless(ref($prices) eq 'ARRAY') {
                my @arr = ($prices);
                $prices = \@arr;
        }

        my $price_flag = 0;
	foreach (@$prices) {
		unless($_=~ /^[0-9]\d*\.?\d*$/) {
			unless($_ eq '0') {
				$price_flag = 1;
			}
		}
	}
        if($price_flag == 1) {
                my $text = "你输入的商品价格不是合法的数字";
                push(@messages, $text);

        }

        my ($tiyan_df, $tiyan_dt);
        if($group_tiyan eq 'y') {
	        eval{
                        $tiyan_df= Time::Piece->strptime($tiyan_time_from, "%m/%e/%Y %H:%M:%S");
                        $tiyan_dt = Time::Piece->strptime($tiyan_time_to, "%m/%e/%Y %H:%M:%S");
                };
                if(!$tiyan_df or !$tiyan_dt or $@){
                        my $text = "体验时间格式不对";
                        push(@messages, $text);

                } else {
                        my $diff = $tiyan_dt - $tiyan_df;
                        if($diff <= 0) {
                                my $text = "体验结束时间应当在开始时间之后";
                                push(@messages, $text);

                        }
                }
        } else {
                $tiyan_df= Time::Piece->strptime("1/1/2000 00:00:00", "%m/%e/%Y %H:%M:%S");
		$tiyan_dt = Time::Piece->strptime("1/1/2000 00:00:00", "%m/%e/%Y %H:%M:%S");
        }

	my ($tihuo_df, $tihuo_dt, $current_time);
	eval{
		$tihuo_df= Time::Piece->strptime($tihuo_time_from, "%m/%e/%Y %H:%M:%S");
		$tihuo_dt = Time::Piece->strptime($tihuo_time_to, "%m/%e/%Y %H:%M:%S");
		#$current_time = Time::Piece->strptime(localtime(), "%m/%e/%Y %H:%M:%S");
	};
	if(!$tihuo_df or !$tihuo_dt or $@){
		my $text = "开截团时间格式不对";
		push(@messages, $text);

	} else {
		my $diff = $tihuo_dt - $tihuo_df;
		#my $curr_diff = $tihuo_df - $current_time;
		if($diff <= 0) {
			my $text = "截团时间应当在开团时间之后";
			push(@messages, $text);
		}
		#else {
		#	if($curr_diff <= 0) {
		#		my $text = "开团时间必须晚于当前时间";
		#		push(@messages, $text);
		#	}
		#}
	}
	if(scalar(@messages) != 0) {
	        $c->stash(login_user => $c->session->{login_user});
                $c->stash(messages => \@messages);
                $c->stash(css   => 'zhuce.css');
                $c->stash(edit_tuan_id   => $tuan_id);
                $c->stash(template => 'tuans/tuan_edit_failed.tt2');	
	} else {
                unless(ref($universities) eq 'ARRAY') {
                        my @arr = ($universities);
                        $universities= \@arr;
                }
                unless(ref($storeIds) eq 'ARRAY') {
                        my @arr = ($storeIds);
                        $storeIds = \@arr;
                }

                my $commented_item = $c->model('CommentedItem::CommentedItemModel')->create('3');
                my $image = $c->request->upload('tuanimage');
	
		if($fahuoshijians ne '-1') {
			$dingqi_group = 'Y';
			if(ref($fahuoshijians) eq 'ARRAY') {
				my $fahuocount = scalar(@$fahuoshijians);
				$yuji_tihuo_time = "";
				while($fahuocount > 0) {
               				my $shijian = $fahuoshijians->[$fahuocount - 1];
               				$yuji_tihuo_time = $yuji_tihuo_time . "|" . $shijian;
					$fahuocount = $fahuocount - 1;
        			}
			}
			else {
				if(($fahuoshijians >= 1) && ($fahuoshijians <= 7)) {
               				$yuji_tihuo_time = "|" . $fahuoshijians;
				}
				else {
					$yuji_tihuo_time = $fahuoshijians;
					(my $dmonth, my $dday,my $dyear) = split(/\//, $yuji_tihuo_time);
					(my $dyear1, my $dtime)  = split(/ /, $dyear);
					$yuji_tihuo_time = $dyear1 . "-" . $dmonth . "-" . $dday;
				}
			}
		}
                $tuan = $c->model('Tuan::TuansCreateModel')->update($image, $c->config->{image_path}, $tuanname, $description, $commented_item->id, $c->user->id, $storeIds, $prices, $group_qitian, $group_tiyan, $group_zhifu, $tihuo_df, $tihuo_dt, $tihuo_location, $tiyan_df, $tiyan_dt, $tiyan_location, $universities, $tuan_id, $yuji_tihuo_time, $dingqi_group);
		
		if($service_num ne '0') {
			my $service = $c->model('OnlineService::OnlineServiceModel')->get_service_num_by_tuan($tuan->id);
			if(defined($service)) {
				$service = $c->model('OnlineService::OnlineServiceModel')->update_by_tuan($tuan->id,$service_num);
			}
			else {
				$service = $c->model('OnlineService::OnlineServiceModel')->create('-1',$tuan->id,$service_num);
			}
		}
		$tuan = $c->model('Tuan::TuansCreateModel')->update_status('A', $tuan_id);
        	$c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));
	}
}

sub jujue:Local {
        my ($self, $c) = @_;

        my $tuan_id = $c->request->params->{tuan_id};
        my $reject_comment = $c->request->params->{reject_comment_hidden};
	my $tuan = $c->model('Tuan::TuansCreateModel')->update_status('N', $tuan_id);
	my $owner_id = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id)->get_column('user_id')->first();	
	my $owner = $c->model('Users::UsersSearchModel')->find($owner_id);		
	my $owner_address = $owner->email_address;		
	my $owner_name= $owner->username;		
	my $title = "您在拼单族申请开通的拼单需要更进一步的信息";
	my $sender = Util::Email::SendEmail->new();
        my $template = "email/rejectTuan.html.tt";
	my $tuan_url = $c->config->{tuan_info_uri} . "/" . $tuan_id . "/tuan_info";
	my (%params, %options);
	$options{INCLUDE_PATH} = $c->config->{email_template_path};
	$params{username} = $owner_name;
	$params{tuanname} = $tuan->name;
	$params{conf_url} = $tuan_url;
	$params{reject_time} = `date`;
	$params{reject_comment} = $reject_comment;
        $sender->send($owner_address, $title, $template, \%params, \%options);
	#如果是拼单转移而来的下游拼单，则修改转移状态
	my $shangyou_tuan_id = $c->model('TuanZhuanYi::TuanZhuanYiModel')->find_shangyou_tuan_id($tuan_id);	
	my $st = $c->model('Tuan::TuansSearchModel')->find($shangyou_tuan_id);
	if (defined $st) {
		my $tzy_id = $c->model('TuanZhuanYi::TuanZhuanYiModel')->find_tzy_id($shangyou_tuan_id,$tuan_id);	
		$c->model('TuanZhuanYi::TuanZhuanYiModel')->update_status($tzy_id,'Z',$c->session->{login_user}->id);	
	}
        $c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));
}

sub pizhun:Local {
        my ($self, $c) = @_;

        my $tuan_id = $c->request->params->{tuan_id};
	#my $one_week_later = `date --date='7 day' +%F`;
	#my $nine_days_later = `date --date='9 day' +%F`;
	#my $tuan = $c->model('Tuan::TuansCreateModel')->update_status('Y', $tuan_id, $one_week_later, $nine_days_later);
	my $tuan = $c->model('Tuan::TuansCreateModel')->update_status('Y', $tuan_id);
	#send mail to group creater
	my $owner_id = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id)->get_column('user_id')->first();	
	my $owner = $c->model('Users::UsersSearchModel')->find($owner_id);		
	my $owner_address = $owner->email_address;		
	my $owner_name= $owner->username;		
	my $title = "您在拼单族的开团申请已被批准";
	my $sender = Util::Email::SendEmail->new();
        my $template = "email/approveTuan.html.tt";
	my $tuan_url = $c->config->{tuan_info_uri} . "/" . $tuan_id . "/tuan_info";
	my (%params, %options);
	$options{INCLUDE_PATH} = $c->config->{email_template_path};
	$params{username} = $owner_name;
	$params{tuanname} = $tuan->name;
	$params{conf_url} = $tuan_url;
	$params{approve_time} = `date`;
        $sender->send($owner_address, $title, $template, \%params, \%options);
	#send mail to user who cares this tuan
	my $storeIds = $c->model('TuanStore::TuanStoreModel')->get_stores_bianhao($tuan_id);
	$title = "您在拼单族关注的商品已经正式开团啦";
	$template = "email/notifyUserTuan.html.tt";
	foreach my $store_id(keys %$storeIds) {
		my $store = $c->model("Store::StoreSearchModel")->find($store_id);
		$params{storename} = $store->name;
		my @users = $c->model('UserStore::UserStoreModel')->get_unnotified_user($store_id)->all;	
		foreach my $user_id1( @users){
			my $emailUser = $c->model('Users::UsersSearchModel')->find($user_id1->user_id);
			$params{username} = $emailUser->username;
			$sender->send($emailUser->email_address, $title, $template, \%params, \%options);			
		}
		$c->model('UserStore::UserStoreModel')->update_notify_status($store_id);
	}
        $c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));

}

sub deliveryGoodsConfirm:Local {
	my ($self, $c) = @_;
	my $user_tuan_id = $c->request->params->{user_tuan_id};
	
	
	#判断该用户是否已经登录
	if(!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
		return 0;
	}

	#判断该用户是否订货用户
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->find($user_tuan_id)->first();
	my $current_id = $c->session->{login_user}->id;
	my @messages;
	if ($current_id ne $user_tuan->user_id ) {
		my $text = "您不能确认该拼单项目，请确保您已正确登录";
		push(@messages, $text);
	}
	if($user_tuan->role ne 'F') {
		my $text = "该订单可能尚未发货，或者已经确认收货，目前不能进行确认操作";
		push(@messages, $text);
	}
	if(scalar(@messages) != 0) {
		$c->stash(login_user => $c->session->{login_user});
                $c->stash(messages => \@messages);
                $c->stash(css   => 'zhuce.css');
                $c->stash(template => 'tuans/delivery_good_confirm_failed.tt2');
	} else {
		$c->model('UserTuan::UserTuanModel')->update_status($user_tuan_id,'Q');
		$c->stash(login_user => $c->session->{login_user});
                $c->stash(css   => 'zhuce.css');
		$c->stash(tuan_id => $user_tuan->tuan_id);
                $c->stash(template => 'tuans/delivery_good_confirm_success.tt2');
	}
	#返回拼单确认页面
}

sub deliveryGoods:Local {
	my ($self, $c) = @_;
	my $user_tuan_id = $c->request->params->{user_tuan_id};
	
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->find($user_tuan_id)->first();
        my $tuan_id = $c->request->params->{tuan_id};
        my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	my $owner_id = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id)->get_column('user_id')->first();
	my $current_id = $c->session->{login_user}->id;
	#只有营长可以发送提醒邮件
	unless($current_id eq $owner_id) {
		$c->stash(login_user => $c->session->{login_user});
		$c->stash(css   => 'zhuce.css');
		$c->stash(template => 'tuans/delivery_good_failed.tt2');
	}
		
	$c->model('UserTuan::UserTuanModel')->update_status($user_tuan_id,'F');
	#发送待确认邮件给参团人员
        my $sender = Util::Email::SendEmail->new();
        my $tuan_url = $c->config->{delivery_confirm_uri} . "?user_tuan_id=" . $user_tuan_id ;
       	my (%params, %options);
       	$options{INCLUDE_PATH} = $c->config->{email_template_path};
       	$params{conf_url} = $tuan_url;
       	$params{approve_time} = `date`;
       	my $title = "请确认您已收到在拼单族订购的商品";
       	my $template = "email/notifyUserDeliveryConfirm.html.tt";
       	$params{tuanname} = $tuan->name;
        my $user_id = $user_tuan->user_id;
        my $emailUser = $c->model('Users::UsersSearchModel')->find($user_id);
        $params{username} = $emailUser->username;
        $sender->send($emailUser->email_address, $title, $template, \%params, \%options);
	
	#返回购买列表页面	
	unless(defined($tuan)) {
		$c->stash(login_user => $c->session->{login_user});
		$c->stash(css   => 'zhuce.css');
		$c->stash(template => 'tuans/buyer_list_failed.tt2');
	}

	my $user_count = $c->model('UserTuanStores::UserTuanStoresModel')->get_user_count($tuan_id);
	my $buy_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_amount($tuan_id);
	my $buyer_details = $c->model('UserTuanStores::UserTuanStoresModel')->get_user_buy_details($tuan_id);
	my $yifahuo_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_yifahuo_amount($tuan_id);
	my $weifahuo_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_weifahuo_amount($tuan_id);
	my $bianhao = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_bianhao($tuan_id);
	my $price = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_price($tuan_id);
	my @user_tuans = $c->model('UserTuan::UserTuanModel')->find_user_tuan_by_tuan_id($tuan_id);
	my $fahuo_count = $c->model('FaHuo::FaHuoModel')->find_next_fahuo_count($tuan_id);

	my %tmp;
	foreach ($tuan->users) {
		$tmp{$_->id} = $_;
	}

	my %users;
	my %user_tuan_id_hash;
	my %new_user_tuans;
	foreach (@user_tuans) {
		my $user_name = $tmp{$_->user_id};
		$user_name = $user_name . "|" . $_->id;
		$users{$user_name} = $tmp{$_->user_id};
		$user_tuan_id_hash{$user_name} = $_->id;
		$new_user_tuans{$_->id} = $_;
	}
	my @sortorder = sort keys %users;	
	
	my $status = 'A';
	my $curr_time = `date --iso-8601=seconds`;
	if($tuan->status eq 'Y') {
		if(str2time($curr_time) < str2time($tuan->tihuo_time_from)) {
			$status = 'W';
		# J表示拼单已截团中
		}elsif(str2time($curr_time) > str2time($tuan->tihuo_time_to)) {
			$status = 'J';
		# P表示拼单进行中
		}else {	
			$status = 'P';
		}	
	}
	if($tuan->status eq 'N') {
		$status = 'N';
	}
	$c->stash(
		login_user => $c->session->{login_user},
		tuan => $tuan,
		css => 'tuan_mainpage.css',
		user_count => $user_count,
		owner_id => $owner_id,
		buy_amount => $buy_amount,
		yifahuo_amount => $yifahuo_amount,
		weifahuo_amount => $weifahuo_amount,
		title => $tuan->name,
		sort_keys => \@sortorder,
		users => \%users,
		fahuo_count => $fahuo_count,
		buyer_details => $buyer_details,
		user_tuan_id_hash => \%user_tuan_id_hash,
		bianhao => $bianhao,
		status => $status,
		price => $price,
		javascript => '/tuan/buyer_detail_list.js',
		user_tuans => \%new_user_tuans,
		template => 'tuans/buyer_list_detailed.tt2');
}

sub notifyDelivery:Local {
       my ($self, $c) = @_;
       my $tuan_id = $c->request->params->{tuan_id};
       my $fa_address = $c->request->params->{fahuo_address_hidden};
       my $fa_time = $c->request->params->{fahuo_time_hidden} || '';
       my $fa_comment= $c->request->params->{fahuo_comment_hidden} || '';
       my $university_id = $c->request->params->{fahuo_university_id_hidden} || '';
       my $university_name = $c->request->params->{fahuo_university_name_hidden} || '';
       my $users= $c->request->params->{fahuo_users_hidden} || '';
       my @arr = split(/,/,$users);
       my @messages;
	if ($fa_time eq '' ) {
		my $text = "您没有输入发货时间";
		push(@messages, $text);
	}
	if ($fa_address eq '') {
		my $text = "您没有输入发货地点";
		push(@messages, $text);
	}
	if ($users eq '') {
		my $text = "您没有选择本次发货通知的用户";
		push(@messages, $text);
	}
	if (scalar(@messages) != 0) {
		$c->stash(login_user => $c->session->{login_user});
                $c->stash(messages => \@messages);
                $c->stash(css   => 'zhuce.css');
                $c->stash(tuan_id => $tuan_id);
                $c->stash(template => 'tuans/notify_delivery_failed.tt2');
		return 1;
	} 
       my $me_id = $c->user->id;
       my $fahuo_count = $c->model('FaHuo::FaHuoModel')->find_next_fahuo_count($tuan_id);
       my $fahuo = $c->model('FaHuo::FaHuoModel')->add_to_fahuo($tuan_id,$fa_time,$fa_address,$fa_comment,$fahuo_count,$me_id);
       $c->model('FaHuoUniversity::FaHuoUniversityModel')->add_to_fahuo_university($fahuo->id,$university_id,$me_id);
       my $univ_text =  '【' . $university_name . '】 ';

       my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
       my $sender = Util::Email::SendEmail->new();
       my $tuan_url = $c->config->{tuan_info_uri} . "/" . $tuan_id . "/tuan_info";
       my (%params, %options);
       $options{INCLUDE_PATH} = $c->config->{email_template_path};
       $params{conf_url} = $tuan_url;
       $params{approve_time} = `date`;
       $params{fa_comment} = $fa_comment;
       $params{fa_time} = $fa_time;
       $params{fa_address} = $fa_address;
       $params{cover_univ} = $univ_text;
       my $title = "【" . $tuan->name . "】发货通知";
       my $template = "email/notifyUserDelivery.html.tt";
       $params{tuanname} = $tuan->name;
       foreach my $user_id (@arr) {
	       my %ding_dan_detail = ();
	       my $emailUser = $c->model('Users::UsersSearchModel')->find($user_id);
	       my @utss = $c->model('UserTuanStores::UserTuanStoresModel')->search_user_tuan_store_by_id($user_id,$tuan_id);
	       my $details = "";
	       foreach my $user_tuan_store(@utss) {
			my $store = $c->model('Store::StoreSearchModel')->find($user_tuan_store->stores_id);
			$ding_dan_detail{$store->name} = $user_tuan_store->amount;
			$details = $details . $store->name . "|" . $user_tuan_store->amount . ";";
	       }
	       #$params{dingdan} = %ding_dan_detail;
	       $params{dingdan} = $details;
	       $params{username} = $emailUser->username;
	       #理论上应该只给尚未发货的订单发送提货通知
	       my $userTuan = $c->model('UserTuan::UserTuanModel')->find_user_tuan($tuan_id, $user_id, 'J');
	       if(!defined($userTuan)) { 
	       		$userTuan = $c->model('UserTuan::UserTuanModel')->find_user_tuan($tuan_id, $user_id, 'F');
	       }
	       if(!defined($userTuan)) { 
	       		$userTuan = $c->model('UserTuan::UserTuanModel')->find_user_tuan($tuan_id, $user_id, 'Q');
	       }
	       if(defined($userTuan)) { 
	       		$params{contact_name} = $userTuan->user_name;
	       		$params{contact_address} = $userTuan->user_address;
	       		$params{contact_phone} = $userTuan->user_cellphone;
	       		$params{password} = $userTuan->password;
	       		$sender->send($emailUser->email_address, $title, $template, \%params, \%options);
	       }
       }
        $c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));

}

sub xiayou_shenqing:Local {
       	my ($self, $c) = @_;
       	my $orig_tuan_id = $c->request->params->{tuan_id};
       	my $shangyou_user_id = $c->request->params->{shangyou_user_id};
       	my $xiayou_user_id = $c->request->params->{xiayou_user_id};

	my $xiayou_user = $c->model('Users::UsersSearchModel')->find($xiayou_user_id);
	my $shangyou_user = $c->model('Users::UsersSearchModel')->find($shangyou_user_id);
	my $target_university = $c->model('University::UniversityModel')->find($xiayou_user->university_id);
       	my $tuan = $c->model('Tuan::TuansSearchModel')->find($orig_tuan_id);
	$c->stash(login_user => $c->session->{login_user},
                javascript => '/store/request_zhuanyi.js',
                css => 'create_new_tuan.css',
                target_university => $target_university,
                xiayou_user => $xiayou_user,
                shangyou_user => $shangyou_user,
                tuan => $tuan,
                template => "stores/request_tuan_zhuanyi.tt2");
}

sub xiayou_zhuanyi_do:Local {
       	my ($self, $c) = @_;
       	my $orig_tuan_id = $c->request->params->{shangyou_tuan_id};
       	my $shangyou_user_id = $c->request->params->{shangyou_user_id};
       	my $xiayou_user_id = $c->request->params->{xiayou_user_id};
       	my $target_univ_id = $c->request->params->{target_univ_id};
       	my $percentage = $c->request->params->{percentage};
       	my $req_detail = $c->request->params->{neirong};
	my $test_request = $c->model('TuanZhuanYi::TuanZhuanYiModel')->find_by_shangyou_tuan_id_requester_id($orig_tuan_id,$xiayou_user_id,$target_univ_id);
	if(defined $test_request) {
		if($test_request->status . '' eq 'R') {
			my $curr_time = `date --iso-8601=seconds`;
			my @message1 = ('您已申请过转移该拼单至目标高校，请不要重复申请。');
			$c->stash(login_user => $c->session->{login_user});
			$c->stash(messages => \@message1);
			$c->stash(curr_time => $curr_time);
       			$c->stash(orig_tuan_id => $orig_tuan_id);
       			$c->stash(shangyou_user_id => $shangyou_user_id);
       			$c->stash(xiayou_user_id => $xiayou_user_id);
			$c->stash(css   => 'zhuce.css');
			$c->stash(template => 'tuans/zhuanyi_create_failed.tt2');
			return 1;
		}
	} 
	my @messages;
	if($percentage eq '') {
	}
	unless($percentage =~ /^[0-9]\d*\.?\d*$/) {
		unless($percentage eq '0') {
			my $text = "您输入的分成比例不合法";
			push(@messages, $text);
		}
	}
	if(scalar(@messages) != 0) {
		my $curr_time = `date --iso-8601=seconds`;
		
		$c->stash(login_user => $c->session->{login_user});
		$c->stash(messages => \@messages);
		$c->stash(curr_time => $curr_time);
       		$c->stash(orig_tuan_id => $orig_tuan_id);
       		$c->stash(shangyou_user_id => $shangyou_user_id);
       		$c->stash(xiayou_user_id => $xiayou_user_id);
		$c->stash(css   => 'zhuce.css');
		$c->stash(template => 'tuans/zhuanyi_create_failed.tt2');
	} else {
	my $request = $c->model('TuanZhuanYi::TuanZhuanYiModel')->request_tuan_zhuanyi($shangyou_user_id,$xiayou_user_id,$orig_tuan_id,$target_univ_id,$percentage,$req_detail, 'R', $xiayou_user_id);
	my $request_complex = $c->model('TuanZhuanYi::TuanZhuanYiModel')->find($request->id);
	my $shangyou_user_id = $request->shangyou_user_id;
        my $shangyou_tuanzhang_info = $c->model('TuanZhang::TuanZhangModel')->tuanzhang_request_search($shangyou_user_id);
        my $shangyou_renzheng_status = 'U'; #'U'表示未提交申请
        if (defined $shangyou_tuanzhang_info) {
                $shangyou_renzheng_status = $shangyou_tuanzhang_info->status;
        }
        my $xiayou_user_id = $request->xiayou_user_id;
        my $xiayou_tuanzhang_info = $c->model('TuanZhang::TuanZhangModel')->tuanzhang_request_search($xiayou_user_id);
        my $xiayou_renzheng_status = 'U'; #'U'表示未提交申请
        if (defined $xiayou_tuanzhang_info) {
                $xiayou_renzheng_status = $xiayou_tuanzhang_info->status;
        }
        my $sender = Util::Email::SendEmail->new();
        my $tzy_url = $c->config->{tzy_info_uri} . "/" . $request->id. "/zhuanyi_info";
       	my (%params, %options);
       	$options{INCLUDE_PATH} = $c->config->{email_template_path};
       	$params{zhuanyi_request} = $request_complex;
       	$params{approve_time} = `date`;
       	$params{username} = $c->session->{login_user}->username;
	$params{conf_url} = $tzy_url;
       	my $title = "您提交了新的拼单转移申请";
       	my $template = "email/notifyXiayouZhuanYi.html.tt";
	if($shangyou_renzheng_status ne 'Y') {
		$params{note} = "上游营长没有经过认证，请注意转移风险";
	}
	$sender->send($c->session->{login_user}->email_address, $title, $template, \%params, \%options);
       	my (%params1, %options1);
       	$options1{INCLUDE_PATH} = $c->config->{email_template_path};
       	$params1{zhuanyi_request} = $request_complex;
       	$params1{approve_time} = `date`;
	$params1{conf_url} = $tzy_url;
       	$params1{username} = $c->session->{login_user}->username;
       	$params1{shangyou_renzheng_status} = $shangyou_renzheng_status;
	my $shangyouUser = $c->model('Users::UsersSearchModel')->find($request_complex->shangyou_user_id);
       	my $title1 = "新的拼单转移申请需要您的审批";
       	my $template1 = "email/notifyShangyouZhuanYi.html.tt";
	
	$sender->send($shangyouUser->email_address, $title1, $template1, \%params1, \%options1);
	$c->stash(
                zhuanyi_request => $request_complex,
                login_user => $c->session->{login_user},
                title => '拼单转移申请',
		css => 'zhuanyi_info.css',
                template => 'zhuanyi/zhuanyi_mainpage.tt2');	
	}

}

sub user_tuan_verification:Local {
	my ( $self, $c ) = @_;
        my $utid = $c->request->params->{"utid"}  || '';
        my $code = $c->request->params->{"code"}  || '';
        my $usertuan = $c->model('UserTuan::UserTuanModel')->find($utid)->first();
	if (!$c->user_exists) {
        	$c->stash(css   => 'zhuce.css');
        	$c->stash(message   => '您尚未登录，没有权限确认该订单，请使用正确的账户登录后再次确认。');
                $c->stash(tuan_id   => $usertuan->get_column('tuan_id'));
        	$c->stash(template => 'tuans/confirm_failed.tt2');	
		return 0;
	}
	my $current_user_id = $c->session->{login_user}->id;
	
	my $ut_user_id = $usertuan->get_column('user_id'); 
        my $user = $c->model('Users::UsersSearchModel')->find($ut_user_id);
	if ($current_user_id != $ut_user_id) {
        	$c->stash(css   => 'zhuce.css');
        	$c->stash(message   => '您没有权限确认该订单，请使用正确的账户登录后再次确认。');
                $c->stash(tuan_id   => $usertuan->get_column('tuan_id'));
        	$c->stash(template => 'tuans/confirm_failed.tt2');	
		return 0;
	}
        if ($usertuan and $usertuan->status ne 'Y') {
                my $md5 = Digest::MD5->new;
                $md5->add($user->email_address . '||' . $utid);
                if ($md5->hexdigest eq $code) {
                        $usertuan->update({status => 'Y'});
                        $c->stash(css   => 'zhuce.css');
                        $c->stash(tuan_id   => $usertuan->get_column('tuan_id'));
                        $c->stash(template => 'tuans/confirm_success.tt2');
                        return;
                }
        }
        my $message = "";
        unless($usertuan) {
                $message = "该验证连接已经失效";
        }
	if($usertuan and $usertuan->status eq 'Y') {
                $message = "您已经验证过此订单";
        }
        $c->stash(css   => 'zhuce.css');
        $c->stash(message   => $message);
        $c->stash(template => 'tuans/confirm_failed.tt2');	
}

sub generate_buyer_deliver_list_csv:Local {
	my ($self, $c) = @_;
	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		return 0;
	}
	my $tuan_id = $c->request->params->{tuan_id};
	
	my $current_user_id = $c->session->{login_user}->id;
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id);
	my $create_user = $c->model('Users::UsersSearchModel')->find($user_tuan->get_column('user_id')->first()); 
	#仅营长可以生成买家详单表格
	my @messages;
	push (@messages, "仅营长可以下载送货详单");
	if ($current_user_id != $create_user->id) {
		$c->stash(
                 	tuan_id => $tuan_id,
                     	login_user => $c->session->{login_user},
                       	title => '操作失败',
                       	messages => \@messages,
                       	css => 'zhuce.css',
                       	template => 'tuans/generate_list_failed.tt2');
		return 1;
	}
		
       	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	my @user_tuans = $c->model('UserTuan::UserTuanModel')->find_user_tuan_by_tuan_id($tuan_id);
	#my $tuanname = $tuan->name;
	my $rand = new String::Random;
        my $t_filename = $rand->randpattern("CCCCCcccccnnnnncccccCCCCC");
	my $filename = $c->config->{image_path} . '/csv/'. $t_filename . '.csv';
	open FH, "+>", $filename
    		or die "could not open $filename: $!\n";
	print FH chr(0xFEFF);
	my $stores = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_bianhao($tuan_id);
	my $prices = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_price_new($tuan_id);
	print FH "序号,姓名,商品,单价,数量,消费金额,发货地址,手机号码\r\n";
	my %storenames;
	my %storeprices;
	my %storecells;
	my $cellN = 0;
	my @storeId;
	while (my ($store_id, $count) = each%{$stores}) {
		my $store_price = $prices->{$store_id};
		my $store = $c->model('Store::StoreSearchModel')->find($store_id);
		$storenames{$store_id} = $store->name;
		$storeprices{$store_id} = $store_price;
		$storecells{$store_id} = $cellN;
		$cellN = $cellN + 1; 	
		push (@storeId, $store_id);
	}
	my $line_num = 0;
	my $total_revenue = 0;
	my $total_count = 0;
	foreach my $user_tuan(@user_tuans) {
		if($user_tuan->role eq 'J') {
			$line_num = $line_num + 1;	
			print FH $line_num . ',';
			my $user_id = $user_tuan->user_id;
			my $user = $c->model('Users::UsersSearchModel')->find($user_id);
			print FH $user_tuan->user_name . ',';
			my $utss = $c->model('UserTuanStores::UserTuanStoresModel')->search($user_tuan->id);
			my @keys = keys %$utss;
			my $current_store_count = 0;
			foreach my $store_id(@storeId) {
				if(exists $utss->{$store_id}) {
					$current_store_count = $current_store_count + 1;
					print FH $storenames{$store_id} . ','; 
					print FH $storeprices{$store_id} . ','; 
					print FH $utss->{$store_id} . ',';	
					my $count = $utss->{$store_id};
					my $sp =  $storeprices{$store_id}; 
					my $jine = $sp * $count;
					$total_revenue = $total_revenue + $jine;
					$total_count = $total_count + $count;
					print FH $jine . ',';	
					print FH $user_tuan->user_address . ',';
					print FH $user_tuan->user_cellphone . ',';
					if($current_store_count == @keys) {	
						print FH "\r\n";
					}	
					else {
						print FH "\r\n,,";
					}
				}
			}
		}
	}
	print FH "总计,,"..",".$total_revenue;
	close (FH);
	$c->response->redirect('/static/images/csv/'. $t_filename . '.csv');
	
}

sub generate_all_buyer_deliver_list_csv:Local {
	my ($self, $c) = @_;
	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		return 0;
	}
	my $current_user_id = $c->session->{login_user}->id;
	my $rand = new String::Random;
        my $t_filename = $rand->randpattern("CCCCCcccccnnnnncccccCCCCC");
	my $filename = $c->config->{image_path} . '/csv/'. $t_filename . '.csv';
	open FH, "+>", $filename
    		or die "could not open $filename: $!\n";
	print FH chr(0xFEFF);

       	my @tuans = $c->model('Tuan::TuansSearchModel')->find_tuans_owned_by_user($current_user_id,'C');
	foreach(@tuans) {
	my $tuan_id = $_->id;
		
       	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	my @user_tuans = $c->model('UserTuan::UserTuanModel')->find_undelivered_user_tuan_by_tuan_id($tuan_id);
	#my $tuanname = $tuan->name;
	if(@user_tuans > 0) {
	my $stores = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_bianhao($tuan_id);
	my $prices = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_price_new($tuan_id);
	print FH $_->name."待发货清单\r\n";
	print FH "序号,姓名,商品,单价,数量,消费金额,发货地址,手机号码\r\n";
	my %storenames;
	my %storeprices;
	my %storecells;
	my $cellN = 0;
	my @storeId;
	while (my ($store_id, $count) = each%{$stores}) {
		my $store_price = $prices->{$store_id};
		my $store = $c->model('Store::StoreSearchModel')->find($store_id);
		$storenames{$store_id} = $store->name;
		$storeprices{$store_id} = $store_price;
		$storecells{$store_id} = $cellN;
		$cellN = $cellN + 1; 	
		push (@storeId, $store_id);
	}
	my $line_num = 0;
	my $total_revenue = 0;
	my $total_count = 0;
	foreach my $user_tuan(@user_tuans) {
		if($user_tuan->role eq 'J') {
			$line_num = $line_num + 1;	
			print FH $line_num . ',';
			my $user_id = $user_tuan->user_id;
			my $user = $c->model('Users::UsersSearchModel')->find($user_id);
			print FH $user_tuan->user_name . ',';
			my $utss = $c->model('UserTuanStores::UserTuanStoresModel')->search($user_tuan->id);
			my @keys = keys %$utss;
			my $current_store_count = 0;
			foreach my $store_id(@storeId) {
				if(exists $utss->{$store_id}) {
					$current_store_count = $current_store_count + 1;
					print FH $storenames{$store_id} . ','; 
					print FH $storeprices{$store_id} . ','; 
					print FH $utss->{$store_id} . ',';	
					my $count = $utss->{$store_id};
					my $sp =  $storeprices{$store_id}; 
					my $jine = $sp * $count;
					$total_revenue = $total_revenue + $jine;
					$total_count = $total_count + $count;
					print FH $jine . ',';	
					print FH $user_tuan->user_address . ',';
					print FH $user_tuan->user_cellphone . ',';
					if($current_store_count == @keys) {	
						print FH "\r\n";
					}	
					else {
						print FH "\r\n,,";
					}
				}
			}
		}
	}
	print FH "\r\n";
	print FH "\r\n";
	print FH "\r\n";
	print FH "\r\n";
	}
	}
	close (FH);
	$c->response->redirect('/static/images/csv/'. $t_filename . '.csv');
	
}

sub generate_all_buyer_deliver_list_csv_for_univ:Local {
	my ($self, $c) = @_;
	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		return 0;
	}
	my $current_user_id = $c->session->{login_user}->id;
	my $user = $c->model('Users::UsersSearchModel')->find($current_user_id);
	my $univ_id = $user->university_id;
	my $univ = $c->model('University::UniversityModel')->find($univ_id);
	my $univ_name = $univ->name;
	my $is_danwei_admin = $c->model('UserTuan::UserTuanModel')->is_danwei_admin($current_user_id,$current_user_id);
	#仅营长可以生成买家详单表格
	my @messages;
	push (@messages, "仅高校管理员可以下载该高校所有买家详单");
	if ($is_danwei_admin ne '1') {
		$c->stash(
                     	login_user => $c->session->{login_user},
                       	title => '操作失败',
                       	messages => \@messages,
                       	css => 'zhuce.css',
                       	template => 'tuans/generate_univ_list_failed.tt2');
		return 1;
	}
		
	my $rand = new String::Random;
        my $t_filename = $rand->randpattern("CCCCCcccccnnnnncccccCCCCC");
	my $filename = $c->config->{image_path} . '/csv/'. $t_filename . '.csv';
	open FH, "+>", $filename
    		or die "could not open $filename: $!\n";
	print FH chr(0xFEFF);
	print FH ",,,,,,,".$univ_name."当前待发货清单\r\n";

       	my $tuans = $c->model('Tuan::TuansSearchModel')->find_tuans_in_university($univ_id);
	foreach(@$tuans) {
	my $tuan_id = $_->id;
		
       	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	my @user_tuans = $c->model('UserTuan::UserTuanModel')->find_undelivered_user_tuan_by_tuan_id($tuan_id);
	#my $tuanname = $tuan->name;
	if(@user_tuans > 0) {
	my $stores = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_bianhao($tuan_id);
	my $prices = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_price_new($tuan_id);
	print FH $_->name."待发货清单\r\n";
	print FH "序号,姓名,商品,单价,数量,消费金额,发货地址,手机号码\r\n";
	my %storenames;
	my %storeprices;
	my %storecells;
	my $cellN = 0;
	my @storeId;
	while (my ($store_id, $count) = each%{$stores}) {
		my $store_price = $prices->{$store_id};
		my $store = $c->model('Store::StoreSearchModel')->find($store_id);
		$storenames{$store_id} = $store->name;
		$storeprices{$store_id} = $store_price;
		$storecells{$store_id} = $cellN;
		$cellN = $cellN + 1; 	
		push (@storeId, $store_id);
	}
	my $line_num = 0;
	my $total_revenue = 0;
	my $total_count = 0;
	foreach my $user_tuan(@user_tuans) {
		if($user_tuan->role eq 'J') {
			$line_num = $line_num + 1;	
			print FH $line_num . ',';
			my $user_id = $user_tuan->user_id;
			my $user = $c->model('Users::UsersSearchModel')->find($user_id);
			print FH $user_tuan->user_name . ',';
			my $utss = $c->model('UserTuanStores::UserTuanStoresModel')->search($user_tuan->id);
			my @keys = keys %$utss;
			my $current_store_count = 0;
			foreach my $store_id(@storeId) {
				if(exists $utss->{$store_id}) {
					$current_store_count = $current_store_count + 1;
					print FH $storenames{$store_id} . ','; 
					print FH $storeprices{$store_id} . ','; 
					print FH $utss->{$store_id} . ',';	
					my $count = $utss->{$store_id};
					my $sp =  $storeprices{$store_id}; 
					my $jine = $sp * $count;
					$total_revenue = $total_revenue + $jine;
					$total_count = $total_count + $count;
					print FH $jine . ',';	
					print FH $user_tuan->user_address . ',';
					print FH $user_tuan->user_cellphone . ',';
					if($current_store_count == @keys) {	
						print FH "\r\n";
					}	
					else {
						print FH "\r\n,,";
					}
				}
			}
		}
	}
	print FH "\r\n";
	print FH "\r\n";
	print FH "\r\n";
	print FH "\r\n";
	}
	}
	close (FH);
	$c->response->redirect('/static/images/csv/'. $t_filename . '.csv');
	
}

sub generate_buyer_list_csv:Local {
	my ($self, $c) = @_;
	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		return 0;
	}
	my $tuan_id = $c->request->params->{tuan_id};
	
	my $current_user_id = $c->session->{login_user}->id;
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id);
	my $create_user = $c->model('Users::UsersSearchModel')->find($user_tuan->get_column('user_id')->first()); 
	#仅营长可以生成买家详单表格
	my @messages;
	push (@messages, "仅营长可以下载买家详单");
	if ($current_user_id != $create_user->id) {
		$c->stash(
                 	tuan_id => $tuan_id,
                     	login_user => $c->session->{login_user},
                       	title => '操作失败',
                       	messages => \@messages,
                       	css => 'zhuce.css',
                       	template => 'tuans/generate_list_failed.tt2');
		return 1;
	}
		
       	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	my @user_tuans = $c->model('UserTuan::UserTuanModel')->find_user_tuan_by_tuan_id($tuan_id);
	#my $tuanname = $tuan->name;
	my $rand = new String::Random;
        my $t_filename = $rand->randpattern("CCCCCcccccnnnnncccccCCCCC");
	my $filename = $c->config->{image_path} . '/csv/'. $t_filename . '.csv';
	open FH, "+>", $filename
    		or die "could not open $filename: $!\n";
	print FH chr(0xFEFF);
	my $stores = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_bianhao($tuan_id);
	my $prices = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_price_new($tuan_id);
	print FH "序号,拼单族ID,参团高校,";
	my %storenames;
	my %storeprices;
	my %storecells;
	my $cellN = 0;
	my @storeId;
	while (my ($store_id, $count) = each%{$stores}) {
		my $store_price = $prices->{$store_id};
		my $store = $c->model('Store::StoreSearchModel')->find($store_id);
		$storenames{$store_id} = $store->name;
		$storeprices{$store_id} = $store_price;
		$storecells{$store_id} = $cellN;
		$cellN = $cellN + 1; 	
		push (@storeId, $store_id);
	}
	foreach my $store_id(@storeId) {
		print FH $storenames{$store_id} . ','; 
	}
	print FH '总金额,订单状态,拼客姓名,手机号码,送货地址,拼客备注,参单时间';
	print FH "\r\n,,拼单价格,";
	foreach my $store_id(@storeId) {
		print FH $storeprices{$store_id} . ','; 
	}
	print FH "\r\n";
	my $line_num = 0;
	my %total_store_count;
	my $total_revenue = 0;
	foreach my $user_tuan(@user_tuans) {
		if($user_tuan->role ne 'C') {
			$line_num = $line_num + 1;	
			print FH $line_num . ',';
			my $user_id = $user_tuan->user_id;
			my $user = $c->model('Users::UsersSearchModel')->find($user_id);
			print FH $user->username . ',';
			my $univ_id = $user_tuan->university_id;
			my $univ = $c->model('University::UniversityModel')->find($univ_id);
			print FH $univ->name . ',';
			my $utss = $c->model('UserTuanStores::UserTuanStoresModel')->search($user_tuan->id);
			my $total = 0;
			foreach my $store_id(@storeId) {
				print FH (exists $utss->{$store_id} ? $utss->{$store_id} : '0') . ',';	
				my $count = (exists $utss->{$store_id} ? $utss->{$store_id} : 0);
				my $sp =  $storeprices{$store_id}; 
				$total = $total + $sp * $count;	
				if(exists $total_store_count{$store_id}) {
					my $current_count = $total_store_count{$store_id};	
					$total_store_count{$store_id} = $current_count + $count;
				}
				else {
					$total_store_count{$store_id} = $count;
				}
			}
			$total_revenue = $total_revenue + $total;
			print FH $total . ",";
			if($user_tuan->status eq 'N') {
				print FH "未确认订单,";
			}
			else {
				if($user_tuan->role eq 'J') {
					print FH "未发货,";
				}
				if($user_tuan->role eq 'F') {
					print FH "已发货,";
				}
				if($user_tuan->role eq 'Q') {
					print FH "已确认收货,";
				}
			}
		 	print FH $user_tuan->user_name;
		 	print FH ",";
		 	print FH $user_tuan->user_cellphone;
		 	print FH ",";
		 	print FH $user_tuan->user_address;
		 	print FH ",";
		 	print FH $user_tuan->jt_comment;
		 	print FH ",";
		 	print FH $user_tuan->created;
			print FH "\r\n";
		}
	}
	print FH ",,总计,";
	foreach my $store_id(@storeId) {
		if(exists $total_store_count{$store_id}) {
			print FH $total_store_count{$store_id}.",";
		}
		else {
			print FH "0,";
		}
	}
	print FH $total_revenue."\r\n";
	close (FH);
	$c->response->redirect('/static/images/csv/'. $t_filename . '.csv');
	
}

sub tihuo_code_use:Local {
	my ($self, $c) = @_;
	my $tihuo_code = $c->request->params->{tihuo_code};
	my $tuan_id = $c->request->params->{tuan_id};
	
	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->find_user_tuan_by_password($tihuo_code, $tuan_id);
	my $owner_id = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id)->get_column('user_id')->first();
	my $current_id = $c->session->{login_user}->id;
	if(defined $user_tuan) {
		if($user_tuan->role eq 'J' && $owner_id eq $current_id ) {
			if($owner_id eq $current_id) {
				$c->model('UserTuan::UserTuanModel')->update_status($user_tuan->id,'F');
        			my $sender = Util::Email::SendEmail->new();
        			my $tuan_url = $c->config->{delivery_confirm_uri} . "?user_tuan_id=" . $user_tuan->id ;
       				my (%params, %options);
       				$options{INCLUDE_PATH} = $c->config->{email_template_path};
       				$params{conf_url} = $tuan_url;
       				$params{approve_time} = `date`;
       				my $title = "提货码已使用";
       				my $template = "email/notifyUserTihuo.html.tt";
       				$params{tuanname} = $tuan->name;
        			my $user_id = $user_tuan->user_id;
        			my $emailUser = $c->model('Users::UsersSearchModel')->find($user_id);
        			$params{username} = $emailUser->username;
        			$params{password} = $tihuo_code;
        			$sender->send($emailUser->email_address, $title, $template, \%params, \%options);
	
				$c->stash(
                			tuan_id => $tuan_id,
                			login_user => $c->session->{login_user},
                			title => '提货码已确认使用',
                			css => 'zhuce.css',
                			template => 'tuans/tihuo_success.tt2');	
				return 0;
			}
			else {
				$c->stash(
                        		tuan_id => $tuan_id,
                        		login_user => $c->session->{login_user},
                        		title => '提货码使用失败',
                        		message => '只有营长可以确认使用提货码',
                        		css => 'zhuce.css',
                        		template => 'tuans/tihuo_failed.tt2');
				return 1;
			}
		}
		else {
			$c->stash(
                        tuan_id => $tuan_id,
                        login_user => $c->session->{login_user},
                        title => '提货码使用失败',
                        message => '该提货码已使用过，无法再次使用',
                        css => 'zhuce.css',
                        template => 'tuans/tihuo_failed.tt2');
                	return 1;		
		}
	}
	else {
		$c->stash(
                        tuan_id => $tuan_id,
                        login_user => $c->session->{login_user},
                        title => '提货码使用失败',
                        message => '非法提货码，无法使用',
                        css => 'zhuce.css',
                        template => 'tuans/tihuo_failed.tt2');
                return 1;		
	}
	
	
		
	
}
	
sub expire_contact:Local {
	my ($self, $c) = @_;
	my $contact_id = $c->request->params->{contact_id};
	my $tuan_id = $c->request->params->{tuan_id};
		
	my $contact = $c->model('UserDeliverContact::UserDeliverContactModel')->expire_contact($contact_id);
        $c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));
}
=head1 AUTHOR

kkkkkk
lijie,,,

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

